<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>Java连接数据库 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="Java连接数据库"><meta property="og:title" content="Java连接数据库" />
<meta property="og:description" content="Java连接数据库" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-02-16T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-02-16T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="Java连接数据库"/>
<meta name="twitter:description" content="Java连接数据库"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" /><link rel="prev" href="https://acking-you.github.io/posts/%E5%BE%92%E6%89%8B%E5%86%99%E7%9A%84avl%E7%AB%9F%E7%84%B6%E6%AF%94stl%E4%B8%AD%E7%9A%84%E7%BA%A2%E9%BB%91%E6%A0%91%E6%95%88%E7%8E%87%E6%9B%B4%E9%AB%98/" /><link rel="next" href="https://acking-you.github.io/posts/c&#43;&#43;%E6%89%8B%E6%92%95%E5%93%88%E5%B8%8C%E8%A1%A8%E8%AF%A6%E8%A7%A3/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Java连接数据库",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93\/"
        },"genre": "posts","keywords": "Java连接数据库","wordcount":  31614 ,
        "url": "https:\/\/acking-you.github.io\/posts\/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93\/","datePublished": "2022-02-16T00:00:00+00:00","dateModified": "2022-02-16T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "Java连接数据库"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        title="Java连接数据库" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">Java连接数据库</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/javaweb%E7%AC%94%E8%AE%B0/"><i class="far fa-folder fa-fw"></i>JavaWeb笔记</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-02-16">2022-02-16</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 31614 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 64 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#初识jdbc">初识JDBC</a>
      <ul>
        <li><a href="#准备工作">准备工作</a></li>
        <li><a href="#使用jdbc连接数据库">使用JDBC连接数据库</a></li>
        <li><a href="#了解drivermanager">了解DriverManager</a></li>
        <li><a href="#了解connection">了解Connection</a></li>
        <li><a href="#了解statement">了解Statement</a></li>
        <li><a href="#执行dml操作">执行DML操作</a></li>
        <li><a href="#执行dql操作">执行DQL操作</a></li>
        <li><a href="#执行批处理操作">执行批处理操作</a></li>
        <li><a href="#将查询结果映射为对象">将查询结果映射为对象</a></li>
        <li><a href="#实现登陆与sql注入攻击">实现登陆与SQL注入攻击</a></li>
        <li><a href="#使用preparedstatement">使用PreparedStatement</a></li>
        <li><a href="#管理事务">管理事务</a></li>
      </ul>
    </li>
    <li><a href="#使用lombok">使用Lombok</a>
      <ul>
        <li><a href="#配置lombok">配置Lombok</a></li>
        <li><a href="#使用lombok-1">使用Lombok</a></li>
      </ul>
    </li>
    <li><a href="#认识mybatis">认识Mybatis</a>
      <ul>
        <li><a href="#xml语言概述">XML语言概述</a></li>
        <li><a href="#初次使用mybatis">初次使用Mybatis</a></li>
        <li><a href="#配置mybatis">配置Mybatis</a></li>
        <li><a href="#增删改查">增删改查</a></li>
        <li><a href="#复杂查询">复杂查询</a></li>
        <li><a href="#事务操作">事务操作</a></li>
        <li><a href="#动态sql">动态SQL</a></li>
        <li><a href="#缓存机制">缓存机制</a></li>
        <li><a href="#使用注解开发">使用注解开发</a></li>
        <li><a href="#探究mybatis的动态代理机制">探究Mybatis的动态代理机制</a></li>
      </ul>
    </li>
    <li><a href="#使用junit进行单元测试">使用JUnit进行单元测试</a>
      <ul>
        <li><a href="#尝试junit">尝试JUnit</a></li>
      </ul>
    </li>
    <li><a href="#jul日志系统">JUL日志系统</a>
      <ul>
        <li><a href="#jul日志讲解">JUL日志讲解</a></li>
        <li><a href="#properties配置文件">Properties配置文件</a></li>
        <li><a href="#编写日志配置文件">编写日志配置文件</a></li>
        <li><a href="#使用lombok快速开启日志">使用Lombok快速开启日志</a></li>
        <li><a href="#mybatis日志系统">Mybatis日志系统</a></li>
      </ul>
    </li>
    <li><a href="#使用maven管理项目">使用Maven管理项目</a>
      <ul>
        <li><a href="#maven项目结构">Maven项目结构</a></li>
        <li><a href="#maven依赖导入">Maven依赖导入</a></li>
        <li><a href="#maven依赖作用域">Maven依赖作用域</a></li>
        <li><a href="#maven可选依赖">Maven可选依赖</a></li>
        <li><a href="#maven排除依赖">Maven排除依赖</a></li>
        <li><a href="#maven继承关系">Maven继承关系</a></li>
        <li><a href="#maven常用命令">Maven常用命令</a></li>
        <li><a href="#maven测试项目">Maven测试项目</a></li>
        <li><a href="#maven打包项目">Maven打包项目</a></li>
      </ul>
    </li>
    <li><a href="#实战基于mybatisjullombokmaven的图书管理系统带单元测试">实战：基于Mybatis+JUL+Lombok+Maven的图书管理系统（带单元测试）</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h1 id="java与数据库">Java与数据库</h1>
<p>通过Java如何去使用数据库来帮助我们存储数据呢，这将是本章节讨论的重点。</p>
<h2 id="初识jdbc">初识JDBC</h2>
<p>JDBC是什么？JDBC英文名为：Java Data Base Connectivity(Java数据库连接)，官方解释它是Java编程语言和广泛的数据库之间独立于数据库的连接标准的Java API，根本上说JDBC是一种规范，它提供的接口，一套完整的，允许便捷式访问底层数据库。可以用JAVA来写不同类型的可执行文件：JAVA应用程序、JAVA Applets、Java Servlet、JSP等，不同的可执行文件都能通过JDBC访问数据库，又兼备存储的优势。简单说它就是Java与数据库的连接的桥梁或者插件，用Java代码就能操作数据库的增删改查、存储过程、事务等。</p>
<p>我们可以发现，JDK自带了一个<code>java.sql</code>包，而这里面就定义了大量的接口，不同类型的数据库，都可以通过实现此接口，编写适用于自己数据库的实现类。而不同的数据库厂商实现的这套标准，我们称为<code>数据库驱动</code>。</p>
<h3 id="准备工作">准备工作</h3>
<p>那么我们首先来进行一些准备工作，以便开始JDBC的学习：</p>
<ul>
<li>将idea连接到我们的数据库，以便以后调试。</li>
<li>将mysql驱动jar依赖导入到项目中（推荐6.0版本以上，这里用到是8.0）</li>
<li>向Jetbrians申请一个学生/教师授权，用于激活idea终极版（进行JavaWeb开发需要用到，一般申请需要3-7天时间审核）不是大学生的话&hellip;emmm&hellip;懂的都懂。</li>
<li>教育授权申请地址：https://www.jetbrains.com/shop/eform/students</li>
</ul>
<p>一个Java程序并不是一个人的战斗，我们可以在别人开发的基础上继续向上开发，其他的开发者可以将自己编写的Java代码打包为<code>jar</code>，我们只需要导入这个<code>jar</code>作为依赖，即可直接使用别人的代码，就像我们直接去使用JDK提供的类一样。</p>
<h3 id="使用jdbc连接数据库">使用JDBC连接数据库</h3>
<p>**注意：**6.0版本以上，不用手动加载驱动，我们直接使用即可！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//1. 通过DriverManager来获得数据库连接
</span><span class="c1"></span><span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;连接URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
     <span class="c1">//2. 创建一个用于执行SQL的Statement对象
</span><span class="c1"></span>     <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>   <span class="c1">//注意前两步都放在try()中，因为在最后需要释放资源！
</span><span class="c1"></span>    <span class="c1">//3. 执行SQL语句，并得到结果集
</span><span class="c1"></span>    <span class="n">ResultSet</span> <span class="n">set</span> <span class="o">=</span> <span class="n">statement</span><span class="o">.</span><span class="na">executeQuery</span><span class="o">(</span><span class="s">&#34;select * from 表名&#34;</span><span class="o">);</span>
    <span class="c1">//4. 查看结果
</span><span class="c1"></span>    <span class="k">while</span> <span class="o">(</span><span class="n">set</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
        <span class="o">...</span>
    <span class="o">}</span>
<span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
    <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
<span class="o">}</span>
<span class="c1">//5. 释放资源，try-with-resource语法会自动帮助我们close
</span></code></pre></div><p>其中，连接的URL如果记不住格式，我们可以打开idea的数据库连接配置，复制一份即可。（其实idea本质也是使用的JDBC，整个idea程序都是由Java编写的，实际上idea就是一个Java程序）</p>
<h3 id="了解drivermanager">了解DriverManager</h3>
<p>我们首先来了解一下DriverManager是什么东西，它其实就是管理我们的数据库驱动的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">registerDriver</span><span class="o">(</span><span class="n">java</span><span class="o">.</span><span class="na">sql</span><span class="o">.</span><span class="na">Driver</span> <span class="n">driver</span><span class="o">,</span>
        <span class="n">DriverAction</span> <span class="n">da</span><span class="o">)</span>
    <span class="kd">throws</span> <span class="n">SQLException</span> <span class="o">{</span>

    <span class="cm">/* Register the driver if it has not already been added to our list */</span>
    <span class="k">if</span><span class="o">(</span><span class="n">driver</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">registeredDrivers</span><span class="o">.</span><span class="na">addIfAbsent</span><span class="o">(</span><span class="k">new</span> <span class="n">DriverInfo</span><span class="o">(</span><span class="n">driver</span><span class="o">,</span> <span class="n">da</span><span class="o">));</span>    <span class="c1">//在刚启动时，mysql实现的驱动会被加载，我们可以断点调试一下。
</span><span class="c1"></span>    <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
        <span class="c1">// This is for compatibility with the original DriverManager
</span><span class="c1"></span>        <span class="k">throw</span> <span class="k">new</span> <span class="n">NullPointerException</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="n">println</span><span class="o">(</span><span class="s">&#34;registerDriver: &#34;</span> <span class="o">+</span> <span class="n">driver</span><span class="o">);</span>

<span class="o">}</span>
</code></pre></div><p>我们可以通过调用getConnection()来进行数据库的链接：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@CallerSensitive</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="n">Connection</span> <span class="nf">getConnection</span><span class="o">(</span><span class="n">String</span> <span class="n">url</span><span class="o">,</span>
    <span class="n">String</span> <span class="n">user</span><span class="o">,</span> <span class="n">String</span> <span class="n">password</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">SQLException</span> <span class="o">{</span>
    <span class="n">java</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">Properties</span> <span class="n">info</span> <span class="o">=</span> <span class="k">new</span> <span class="n">java</span><span class="o">.</span><span class="na">util</span><span class="o">.</span><span class="na">Properties</span><span class="o">();</span>

    <span class="k">if</span> <span class="o">(</span><span class="n">user</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">info</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;user&#34;</span><span class="o">,</span> <span class="n">user</span><span class="o">);</span>
    <span class="o">}</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">password</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">info</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;password&#34;</span><span class="o">,</span> <span class="n">password</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="k">return</span> <span class="o">(</span><span class="n">getConnection</span><span class="o">(</span><span class="n">url</span><span class="o">,</span> <span class="n">info</span><span class="o">,</span> <span class="n">Reflection</span><span class="o">.</span><span class="na">getCallerClass</span><span class="o">()));</span>   <span class="c1">//内部有实现
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们可以手动为驱动管理器添加一个日志打印：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">static</span> <span class="o">{</span>
    <span class="n">DriverManager</span><span class="o">.</span><span class="na">setLogWriter</span><span class="o">(</span><span class="k">new</span> <span class="n">PrintWriter</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">));</span>   <span class="c1">//这里直接设定为控制台输出
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>现在我们执行的数据库操作日志会在控制台实时打印。</p>
<h3 id="了解connection">了解Connection</h3>
<p>Connection是数据库的连接对象，可以通过连接对象来创建一个Statement用于执行SQL语句：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Statement</span> <span class="nf">createStatement</span><span class="o">()</span> <span class="kd">throws</span> <span class="n">SQLException</span><span class="o">;</span>
</code></pre></div><p>我们发现除了普通的Statement，还存在PreparedStatement：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">PreparedStatement</span> <span class="nf">prepareStatement</span><span class="o">(</span><span class="n">String</span> <span class="n">sql</span><span class="o">)</span>
    <span class="kd">throws</span> <span class="n">SQLException</span><span class="o">;</span>
</code></pre></div><p>在后面我们会详细介绍PreparedStatement的使用，它能够有效地预防SQL注入式攻击。</p>
<p>它还支持事务的处理，也放到后面来详细进行讲解。</p>
<h3 id="了解statement">了解Statement</h3>
<p>我们发现，我们之前使用了<code>executeQuery()</code>方法来执行<code>select</code>语句，此方法返回给我们一个ResultSet对象，查询得到的数据，就存放在ResultSet中！</p>
<p>Statement除了执行这样的DQL语句外，我们还可以使用<code>executeUpdate()</code>方法来执行一个DML或是DDL语句，它会返回一个int类型，表示执行后受影响的行数，可以通过它来判断DML语句是否执行成功。</p>
<p>也可以通过<code>excute()</code>来执行任意的SQL语句，它会返回一个<code>boolean</code>来表示执行结果是一个ResultSet还是一个int，我们可以通过使用<code>getResultSet()</code>或是<code>getUpdateCount()</code>来获取。</p>
<h3 id="执行dml操作">执行DML操作</h3>
<p>我们通过几个例子来向数据库中插入数据。</p>
<h3 id="执行dql操作">执行DQL操作</h3>
<p>执行DQL操作会返回一个ResultSet对象，我们来看看如何从ResultSet中去获取数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//首先要明确，select返回的数据类似于一个excel表格
</span><span class="c1"></span><span class="k">while</span> <span class="o">(</span><span class="n">set</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
    <span class="c1">//每调用一次next()就会向下移动一行，首次调用会移动到第一行
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们在移动行数后，就可以通过set中提供的方法，来获取每一列的数据。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F202005062358238.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1JlZ2lubw%3D%3D%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638091193&amp;t=bf37a5cb988d0a641d00c7e325d06ce7"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F202005062358238.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1JlZ2lubw%3D%3D%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638091193&amp;t=bf37a5cb988d0a641d00c7e325d06ce7, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F202005062358238.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1JlZ2lubw%3D%3D%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638091193&amp;t=bf37a5cb988d0a641d00c7e325d06ce7 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F202005062358238.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1JlZ2lubw%3D%3D%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638091193&amp;t=bf37a5cb988d0a641d00c7e325d06ce7 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F202005062358238.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1JlZ2lubw%3D%3D%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638091193&amp;t=bf37a5cb988d0a641d00c7e325d06ce7"
        title="img" /></p>
<h3 id="执行批处理操作">执行批处理操作</h3>
<p>当我们要执行很多条语句时，可以不用一次一次地提交，而是一口气全部交给数据库处理，这样会节省很多的时间。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">();</span>
         <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>

        <span class="n">statement</span><span class="o">.</span><span class="na">addBatch</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;f&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="n">statement</span><span class="o">.</span><span class="na">addBatch</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;e&#39;, 1234)&#34;</span><span class="o">);</span>   <span class="c1">//添加每一条批处理语句
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeBatch</span><span class="o">();</span>   <span class="c1">//一起执行
</span><span class="c1"></span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><h3 id="将查询结果映射为对象">将查询结果映射为对象</h3>
<p>既然我们现在可以从数据库中获取数据了，那么现在就可以将这些数据转换为一个类来进行操作，首先定义我们的实体类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="n">Integer</span> <span class="n">sid</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(</span><span class="n">Integer</span> <span class="n">sid</span><span class="o">,</span> <span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">sex</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">sid</span> <span class="o">=</span> <span class="n">sid</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">sex</span> <span class="o">=</span> <span class="n">sex</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">say</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我叫：&#34;</span><span class="o">+</span><span class="n">name</span><span class="o">+</span><span class="s">&#34;，学号为：&#34;</span><span class="o">+</span><span class="n">sid</span><span class="o">+</span><span class="s">&#34;，我的性别是：&#34;</span><span class="o">+</span><span class="n">sex</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在我们来进行一个转换：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">while</span> <span class="o">(</span><span class="n">set</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
    <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="n">set</span><span class="o">.</span><span class="na">getInt</span><span class="o">(</span><span class="n">1</span><span class="o">),</span> <span class="n">set</span><span class="o">.</span><span class="na">getString</span><span class="o">(</span><span class="n">2</span><span class="o">),</span> <span class="n">set</span><span class="o">.</span><span class="na">getString</span><span class="o">(</span><span class="n">3</span><span class="o">));</span>
    <span class="n">student</span><span class="o">.</span><span class="na">say</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>**注意：**列的下标是从1开始的。</p>
<p>我们也可以利用反射机制来将查询结果映射为对象，使用反射的好处是，无论什么类型都可以通过我们的方法来进行实体类型映射：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">private</span> <span class="kd">static</span> <span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">T</span> <span class="nf">convert</span><span class="o">(</span><span class="n">ResultSet</span> <span class="n">set</span><span class="o">,</span> <span class="n">Class</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">clazz</span><span class="o">){</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">Constructor</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">constructor</span> <span class="o">=</span> <span class="n">clazz</span><span class="o">.</span><span class="na">getConstructor</span><span class="o">(</span><span class="n">clazz</span><span class="o">.</span><span class="na">getConstructors</span><span class="o">()[</span><span class="n">0</span><span class="o">].</span><span class="na">getParameterTypes</span><span class="o">());</span>   <span class="c1">//默认获取第一个构造方法
</span><span class="c1"></span>        <span class="n">Class</span><span class="o">&lt;?&gt;[]</span> <span class="n">param</span> <span class="o">=</span> <span class="n">constructor</span><span class="o">.</span><span class="na">getParameterTypes</span><span class="o">();</span>  <span class="c1">//获取参数列表
</span><span class="c1"></span>        <span class="n">Object</span><span class="o">[]</span> <span class="n">object</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Object</span><span class="o">[</span><span class="n">param</span><span class="o">.</span><span class="na">length</span><span class="o">];</span>  <span class="c1">//存放参数
</span><span class="c1"></span>        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">param</span><span class="o">.</span><span class="na">length</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>   <span class="c1">//是从1开始的
</span><span class="c1"></span>            <span class="n">object</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">=</span> <span class="n">set</span><span class="o">.</span><span class="na">getObject</span><span class="o">(</span><span class="n">i</span><span class="o">+</span><span class="n">1</span><span class="o">);</span>
            <span class="k">if</span><span class="o">(</span><span class="n">object</span><span class="o">[</span><span class="n">i</span><span class="o">].</span><span class="na">getClass</span><span class="o">()</span> <span class="o">!=</span> <span class="n">param</span><span class="o">[</span><span class="n">i</span><span class="o">])</span>
                <span class="k">throw</span> <span class="k">new</span> <span class="n">SQLException</span><span class="o">(</span><span class="s">&#34;错误的类型转换：&#34;</span><span class="o">+</span><span class="n">object</span><span class="o">[</span><span class="n">i</span><span class="o">].</span><span class="na">getClass</span><span class="o">()+</span><span class="s">&#34; -&gt; &#34;</span><span class="o">+</span><span class="n">param</span><span class="o">[</span><span class="n">i</span><span class="o">]);</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="n">constructor</span><span class="o">.</span><span class="na">newInstance</span><span class="o">(</span><span class="n">object</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">ReflectiveOperationException</span> <span class="o">|</span> <span class="n">SQLException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在我们就可以通过我们的方法来将查询结果转换为一个对象了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">while</span> <span class="o">(</span><span class="n">set</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
    <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="n">convert</span><span class="o">(</span><span class="n">set</span><span class="o">,</span> <span class="n">Student</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
    <span class="k">if</span><span class="o">(</span><span class="n">student</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="n">student</span><span class="o">.</span><span class="na">say</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>实际上，在后面我们会学习Mybatis框架，它对JDBC进行了深层次的封装，而它就进行类似上面反射的操作来便于我们对数据库数据与实体类的转换。</p>
<h3 id="实现登陆与sql注入攻击">实现登陆与SQL注入攻击</h3>
<p>在使用之前，我们先来看看如果我们想模拟登陆一个用户，我们该怎么去写：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
     <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">();</span>
     <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">)){</span>
    <span class="n">ResultSet</span> <span class="n">res</span> <span class="o">=</span> <span class="n">statement</span><span class="o">.</span><span class="na">executeQuery</span><span class="o">(</span><span class="s">&#34;select * from user where username=&#39;&#34;</span><span class="o">+</span><span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">()+</span><span class="s">&#34;&#39;and pwd=&#39;&#34;</span><span class="o">+</span><span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">()+</span><span class="s">&#34;&#39;;&#34;</span><span class="o">);</span>
    <span class="k">while</span> <span class="o">(</span><span class="n">res</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
        <span class="n">String</span> <span class="n">username</span> <span class="o">=</span> <span class="n">res</span><span class="o">.</span><span class="na">getString</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">username</span><span class="o">+</span><span class="s">&#34; 登陆成功！&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
    <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>用户可以通过自己输入用户名和密码来登陆，乍一看好像没啥问题，那如果我输入的是以下内容呢：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="n">Test</span><span class="w">
</span><span class="w"></span><span class="mi">1111</span><span class="s1">&#39; or 1=1; -- 
</span><span class="s1"># Test 登陆成功！
</span></code></pre></div><p>1=1一定是true，那么我们原本的SQL语句会变为：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="k">select</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="k">from</span><span class="w"> </span><span class="k">user</span><span class="w"> </span><span class="k">where</span><span class="w"> </span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;Test&#39;</span><span class="w"> </span><span class="k">and</span><span class="w"> </span><span class="n">pwd</span><span class="o">=</span><span class="s1">&#39;1111&#39;</span><span class="w"> </span><span class="k">or</span><span class="w"> </span><span class="mi">1</span><span class="o">=</span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">-- &#39;
</span></code></pre></div><p>我们发现，如果允许这样的数据插入，那么我们原有的SQL语句结构就遭到了破坏，使得用户能够随意登陆别人的账号。因此我们可能需要限制用户的输入来防止用户输入一些SQL语句关键字，但是关键字非常多，这并不是解决问题的最好办法。</p>
<h3 id="使用preparedstatement">使用PreparedStatement</h3>
<p>我们发现，如果单纯地使用Statement来执行SQL命令，会存在严重的SQL注入攻击漏洞！而这种问题，我们可以使用PreparedStatement来解决：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
         <span class="n">PreparedStatement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">prepareStatement</span><span class="o">(</span><span class="s">&#34;select * from user where username= ? and pwd=?;&#34;</span><span class="o">);</span>
         <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">)){</span>

        <span class="n">statement</span><span class="o">.</span><span class="na">setString</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">());</span>
        <span class="n">statement</span><span class="o">.</span><span class="na">setString</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">());</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">statement</span><span class="o">);</span>    <span class="c1">//打印查看一下最终执行的
</span><span class="c1"></span>        <span class="n">ResultSet</span> <span class="n">res</span> <span class="o">=</span> <span class="n">statement</span><span class="o">.</span><span class="na">executeQuery</span><span class="o">();</span>
        <span class="k">while</span> <span class="o">(</span><span class="n">res</span><span class="o">.</span><span class="na">next</span><span class="o">()){</span>
            <span class="n">String</span> <span class="n">username</span> <span class="o">=</span> <span class="n">res</span><span class="o">.</span><span class="na">getString</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">username</span><span class="o">+</span><span class="s">&#34; 登陆成功！&#34;</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，我们需要提前给到PreparedStatement一个SQL语句，并且使用<code>?</code>作为占位符，它会预编译一个SQL语句，通过直接将我们的内容进行替换的方式来填写数据。使用这种方式，我们之前的例子就失效了！我们来看看实际执行的SQL语句是什么：</p>
<pre><code>com.mysql.cj.jdbc.ClientPreparedStatement: select * from user where username= 'Test' and pwd='123456'' or 1=1; -- ';
</code></pre><p>我们发现，我们输入的参数一旦出现<code>'</code>时，会被变为转义形式<code>\'</code>，而最外层有一个真正的<code>'</code>来将我们输入的内容进行包裹，因此它能够有效地防止SQL注入攻击！</p>
<h3 id="管理事务">管理事务</h3>
<p>JDBC默认的事务处理行为是自动提交，所以前面我们执行一个SQL语句就会被直接提交（相当于没有启动事务），所以JDBC需要进行事务管理时，首先要通过Connection对象调用setAutoCommit(false) 方法, 将SQL语句的提交（commit）由驱动程序转交给应用程序负责。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">con</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">();</span>   <span class="c1">//关闭自动提交后相当于开启事务。
</span><span class="c1">// SQL语句
</span><span class="c1">// SQL语句
</span><span class="c1">// SQL语句
</span><span class="c1"></span><span class="n">con</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span><span class="n">或</span> <span class="n">con</span><span class="o">.</span><span class="na">rollback</span><span class="o">();</span>
</code></pre></div><p>一旦关闭自动提交，那么现在执行所有的操作如果在最后不进行<code>commit()</code>来提交事务的话，那么所有的操作都会丢失，只有提交之后，所有的操作才会被保存！也可以使用<code>rollback()</code>来手动回滚之前的全部操作！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
         <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>  <span class="c1">//关闭自动提交，现在将变为我们手动提交
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;a&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;b&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;c&#39;, 1234)&#34;</span><span class="o">);</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>   <span class="c1">//如果前面任何操作出现异常，将不会执行commit()，之前的操作也就不会生效
</span><span class="c1"></span>    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们来接着尝试一下使用回滚操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
         <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>  <span class="c1">//关闭自动提交，现在将变为我们手动提交
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;a&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;b&#39;, 1234)&#34;</span><span class="o">);</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">rollback</span><span class="o">();</span>   <span class="c1">//回滚，撤销前面全部操作
</span><span class="c1"></span>
        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;c&#39;, 1234)&#34;</span><span class="o">);</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>   <span class="c1">//提交事务（注意，回滚之前的内容都没了）
</span><span class="c1"></span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>同样的，我们也可以去创建一个回滚点来实现定点回滚：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
         <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>  <span class="c1">//关闭自动提交，现在将变为我们手动提交
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;a&#39;, 1234)&#34;</span><span class="o">);</span>
        
        <span class="n">Savepoint</span> <span class="n">savepoint</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">setSavepoint</span><span class="o">();</span>   <span class="c1">//创建回滚点
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;b&#39;, 1234)&#34;</span><span class="o">);</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">rollback</span><span class="o">(</span><span class="n">savepoint</span><span class="o">);</span>   <span class="c1">//回滚到回滚点，撤销前面全部操作
</span><span class="c1"></span>
        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;c&#39;, 1234)&#34;</span><span class="o">);</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>   <span class="c1">//提交事务（注意，回滚之前的内容都没了）
</span><span class="c1"></span>
    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>通过开启事务，我们就可以更加谨慎地进行一些操作了，如果我们想从事务模式切换为原有的自动提交模式，我们可以直接将其设置回去：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">ClassNotFoundException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">Connection</span> <span class="n">connection</span> <span class="o">=</span> <span class="n">DriverManager</span><span class="o">.</span><span class="na">getConnection</span><span class="o">(</span><span class="s">&#34;URL&#34;</span><span class="o">,</span><span class="s">&#34;用户名&#34;</span><span class="o">,</span><span class="s">&#34;密码&#34;</span><span class="o">);</span>
         <span class="n">Statement</span> <span class="n">statement</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="na">createStatement</span><span class="o">()){</span>

        <span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>  <span class="c1">//关闭自动提交，现在将变为我们手动提交
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;a&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="n">connection</span><span class="o">.</span><span class="na">setAutoCommit</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>   <span class="c1">//重新开启自动提交，开启时把之前的事务模式下的内容给提交了
</span><span class="c1"></span>        <span class="n">statement</span><span class="o">.</span><span class="na">executeUpdate</span><span class="o">(</span><span class="s">&#34;insert into user values (&#39;d&#39;, 1234)&#34;</span><span class="o">);</span>
        <span class="c1">//没有commit也成功了！
</span><span class="c1"></span>    <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">SQLException</span> <span class="n">e</span><span class="o">){</span>
        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
    <span class="o">}</span>

</code></pre></div><p>通过学习JDBC，我们现在就可以通过Java来访问和操作我们的数据库了！为了更好地衔接，我们还会接着讲解主流持久层框架——Mybatis，加深JDBC的记忆。</p>
<hr>
<h2 id="使用lombok">使用Lombok</h2>
<p>我们发现，在以往编写项目时，尤其是在类进行类内部成员字段封装时，需要编写大量的get/set方法，这不仅使得我们类定义中充满了get和set方法，同时如果字段名称发生改变，又要挨个进行修改，甚至当字段变得很多时，构造方法的编写会非常麻烦！</p>
<p>通过使用Lombok（小辣椒）就可以解决这样的问题！</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F14004711543%2F1000&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638080575&amp;t=91a3937a42d14fe8129b3761bbdef82c"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F14004711543%2F1000&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638080575&amp;t=91a3937a42d14fe8129b3761bbdef82c, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F14004711543%2F1000&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638080575&amp;t=91a3937a42d14fe8129b3761bbdef82c 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F14004711543%2F1000&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638080575&amp;t=91a3937a42d14fe8129b3761bbdef82c 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F14004711543%2F1000&amp;refer=http%3A%2F%2Finews.gtimg.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638080575&amp;t=91a3937a42d14fe8129b3761bbdef82c"
        title="img" /></p>
<p>我们来看看，使用原生方式和小辣椒方式编写类的区别，首先是传统方式：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">Integer</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(</span><span class="n">Integer</span> <span class="n">sid</span><span class="o">,</span> <span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">sex</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">sid</span> <span class="o">=</span> <span class="n">sid</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">sex</span> <span class="o">=</span> <span class="n">sex</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">Integer</span> <span class="nf">getSid</span><span class="o">()</span> <span class="o">{</span>             <span class="c1">//长！
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">sid</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setSid</span><span class="o">(</span><span class="n">Integer</span> <span class="n">sid</span><span class="o">)</span> <span class="o">{</span>     <span class="c1">//到！
</span><span class="c1"></span>        <span class="k">this</span><span class="o">.</span><span class="na">sid</span> <span class="o">=</span> <span class="n">sid</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span>             <span class="c1">//爆！
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">name</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setName</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span>    <span class="c1">//炸！
</span><span class="c1"></span>        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getSex</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">sex</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setSex</span><span class="o">(</span><span class="n">String</span> <span class="n">sex</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">sex</span> <span class="o">=</span> <span class="n">sex</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>而使用Lombok之后：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Getter</span>
<span class="nd">@Setter</span>
<span class="nd">@AllArgsConstructor</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">Integer</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，使用Lombok之后，只需要添加几个注解，就能够解决掉我们之前长长的一串代码！</p>
<h3 id="配置lombok">配置Lombok</h3>
<ul>
<li>首先我们需要导入Lombok的jar依赖，和jdbc依赖是一样的，放在项目目录下直接导入就行了。可以在这里进行下载：https://projectlombok.org/download</li>
<li>然后我们要安装一下Lombok插件，由于IDEA默认都安装了Lombok的插件，因此直接导入依赖后就可以使用了。</li>
<li>重启IDEA</li>
</ul>
<p>Lombok是一种插件化注解API，是通过添加注解来实现的，然后在javac进行编译的时候，进行处理。</p>
<p>Java的编译过程可以分成三个阶段：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://imgconvert.csdnimg.cn/aHR0cDovL29wZW5qZGsuamF2YS5uZXQvZ3JvdXBzL2NvbXBpbGVyL2RvYy9jb21waWxhdGlvbi1vdmVydmlldy9qYXZhYy1mbG93LnBuZw?x-oss-process=image/format,png"
        data-srcset="https://imgconvert.csdnimg.cn/aHR0cDovL29wZW5qZGsuamF2YS5uZXQvZ3JvdXBzL2NvbXBpbGVyL2RvYy9jb21waWxhdGlvbi1vdmVydmlldy9qYXZhYy1mbG93LnBuZw?x-oss-process=image/format%2cpng, https://imgconvert.csdnimg.cn/aHR0cDovL29wZW5qZGsuamF2YS5uZXQvZ3JvdXBzL2NvbXBpbGVyL2RvYy9jb21waWxhdGlvbi1vdmVydmlldy9qYXZhYy1mbG93LnBuZw?x-oss-process=image/format%2cpng 1.5x, https://imgconvert.csdnimg.cn/aHR0cDovL29wZW5qZGsuamF2YS5uZXQvZ3JvdXBzL2NvbXBpbGVyL2RvYy9jb21waWxhdGlvbi1vdmVydmlldy9qYXZhYy1mbG93LnBuZw?x-oss-process=image/format%2cpng 2x"
        data-sizes="auto"
        alt="https://imgconvert.csdnimg.cn/aHR0cDovL29wZW5qZGsuamF2YS5uZXQvZ3JvdXBzL2NvbXBpbGVyL2RvYy9jb21waWxhdGlvbi1vdmVydmlldy9qYXZhYy1mbG93LnBuZw?x-oss-process=image/format,png"
        title="img" /></p>
<ol>
<li>所有源文件会被解析成语法树。</li>
<li>调用注解处理器。如果注解处理器产生了新的源文件，新文件也要进行编译。</li>
<li>最后，语法树会被分析并转化成类文件。</li>
</ol>
<p>实际上在上述的第二阶段，会执行*<a href="https://github.com/rzwitserloot/lombok/blob/master/src/core/lombok/core/AnnotationProcessor.java" target="_blank" rel="noopener noreffer">lombok.core.AnnotationProcessor</a>*，它所做的工作就是我们上面所说的，修改语法树。</p>
<h3 id="使用lombok-1">使用Lombok</h3>
<p>我们通过实战来演示一下Lombok的实用注解：</p>
<ul>
<li>我们通过添加<code>@Getter</code>和<code>@Setter</code>来为当前类的所有字段生成get/set方法，他们可以添加到类或是字段上，注意静态字段不会生成，final字段无法生成set方法。
<ul>
<li>我们还可以使用@Accessors来控制生成Getter和Setter的样式。</li>
</ul>
</li>
<li>我们通过添加<code>@ToString</code>来为当前类生成预设的toString方法。</li>
<li>我们可以通过添加<code>@EqualsAndHashCode</code>来快速生成比较和哈希值方法。</li>
<li>我们可以通过添加<code>@AllArgsConstructor</code>和<code>@NoArgsConstructor</code>来快速生成全参构造和无参构造。</li>
<li>我们可以添加<code>@RequiredArgsConstructor</code>来快速生成参数只包含<code>final</code>或被标记为<code>@NonNull</code>的成员字段。</li>
<li>使用<code>@Data</code>能代表<code>@Setter</code>、<code>@Getter</code>、<code>@RequiredArgsConstructor</code>、<code>@ToString</code>、<code>@EqualsAndHashCode</code>全部注解。
<ul>
<li>一旦使用<code>@Data</code>就不建议此类有继承关系，因为<code>equal</code>方法可能不符合预期结果（尤其是仅比较子类属性）。</li>
</ul>
</li>
<li>使用<code>@Value</code>与<code>@Data</code>类似，但是并不会生成setter并且成员属性都是final的。</li>
<li>使用<code>@SneakyThrows</code>来自动生成try-catch代码块。</li>
<li>使用<code>@Cleanup</code>作用与局部变量，在最后自动调用其<code>close()</code>方法（可以自由更换）</li>
<li>使用<code>@Builder</code>来快速生成建造者模式。
<ul>
<li>通过使用<code>@Builder.Default</code>来指定默认值。</li>
<li>通过使用<code>@Builder.ObtainVia</code>来指定默认值的获取方式。</li>
</ul>
</li>
</ul>
<hr>
<h2 id="认识mybatis">认识Mybatis</h2>
<p>在前面JDBC的学习中，虽然我们能够通过JDBC来连接和操作数据库，但是哪怕只是完成一个SQL语句的执行，都需要编写大量的代码，更不用说如果我还需要进行实体类映射，将数据转换为我们可以直接操作的实体类型，JDBC很方便，但是还不够方便，我们需要一种更加简洁高效的方式来和数据库进行交互。</p>
<p>**再次强调：**学习厉害的框架或是厉害的技术，并不是为了一定要去使用它，而是它们能够使得我们在不同的开发场景下，合理地使用这些技术，以灵活地应对需要解决的问题。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F26720164-60462fc7927f8784.jpg&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638550660&amp;t=a0923b35afbaed1a168b74eb45ad2b4f"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F26720164-60462fc7927f8784.jpg&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638550660&amp;t=a0923b35afbaed1a168b74eb45ad2b4f, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F26720164-60462fc7927f8784.jpg&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638550660&amp;t=a0923b35afbaed1a168b74eb45ad2b4f 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F26720164-60462fc7927f8784.jpg&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638550660&amp;t=a0923b35afbaed1a168b74eb45ad2b4f 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F26720164-60462fc7927f8784.jpg&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1638550660&amp;t=a0923b35afbaed1a168b74eb45ad2b4f"
        title="img" /></p>
<p>MyBatis 是一款优秀的持久层框架，它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息，将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。</p>
<p>我们依然使用传统的jar依赖方式，从最原始开始讲起，不使用Maven，有关Maven内容我们会在后面统一讲解！全程围绕官方文档讲解！</p>
<p>这一块内容很多很杂，再次强调要多实践！</p>
<h3 id="xml语言概述">XML语言概述</h3>
<p>在开始介绍Mybatis之前，XML语言发明最初是用于数据的存储和传输，它可以长这样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34; ?&gt;</span>
<span class="nt">&lt;outer&gt;</span>
  <span class="nt">&lt;name&gt;</span>阿伟<span class="nt">&lt;/name&gt;</span>
  <span class="nt">&lt;desc&gt;</span>怎么又在玩电动啊<span class="nt">&lt;/desc&gt;</span>
	<span class="nt">&lt;inner</span> <span class="na">type=</span><span class="s">&#34;1&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;age&gt;</span>10<span class="nt">&lt;/age&gt;</span>
    <span class="nt">&lt;sex&gt;</span>男<span class="nt">&lt;/sex&gt;</span>
  <span class="nt">&lt;/inner&gt;</span>
<span class="nt">&lt;/outer&gt;</span>
</code></pre></div><p>如果你学习过前端知识，你会发现它和HTML几乎长得一模一样！但是请注意，虽然它们长得差不多，但是他们的意义却不同，HTML主要用于通过编排来展示数据，而XML主要是存放数据，它更像是一个配置文件！当然，浏览器也是可以直接打开XML文件的。</p>
<p>一个XML文件存在以下的格式规范：</p>
<ul>
<li>必须存在一个根节点，将所有的子标签全部包含。</li>
<li>可以但不必须包含一个头部声明（主要是可以设定编码格式）</li>
<li>所有的标签必须成对出现，可以嵌套但不能交叉嵌套</li>
<li>区分大小写。</li>
<li>标签中可以存在属性，比如上面的<code>type=&quot;1&quot;</code>就是<code>inner</code>标签的一个属性，属性的值由单引号或双引号包括。</li>
</ul>
<p>XML文件也可以使用注释：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34; ?&gt;</span>
<span class="c">&lt;!-- 注释内容 --&gt;</span>
</code></pre></div><p>通过IDEA我们可以使用<code>Ctrl</code>+<code>/</code>来快速添加注释文本（不仅仅适用于XML，还支持很多种类型的文件）</p>
<p>那如果我们的内容中出现了<code>&lt;</code>或是<code>&gt;</code>字符，那该怎么办呢？我们就可以使用XML的转义字符来代替：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jxdoc.com%2Fpic%2F28d1ff67caaedd3383c4d358%2F1-332-jpg_6_0_______-505-0-0-505.jpg&amp;refer=http%3A%2F%2Fimg.jxdoc.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639322216&amp;t=88d1ea1adb9cbf1611eaf4c9fa16b8b0"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jxdoc.com%2Fpic%2F28d1ff67caaedd3383c4d358%2F1-332-jpg_6_0_______-505-0-0-505.jpg&amp;refer=http%3A%2F%2Fimg.jxdoc.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639322216&amp;t=88d1ea1adb9cbf1611eaf4c9fa16b8b0, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jxdoc.com%2Fpic%2F28d1ff67caaedd3383c4d358%2F1-332-jpg_6_0_______-505-0-0-505.jpg&amp;refer=http%3A%2F%2Fimg.jxdoc.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639322216&amp;t=88d1ea1adb9cbf1611eaf4c9fa16b8b0 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jxdoc.com%2Fpic%2F28d1ff67caaedd3383c4d358%2F1-332-jpg_6_0_______-505-0-0-505.jpg&amp;refer=http%3A%2F%2Fimg.jxdoc.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639322216&amp;t=88d1ea1adb9cbf1611eaf4c9fa16b8b0 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jxdoc.com%2Fpic%2F28d1ff67caaedd3383c4d358%2F1-332-jpg_6_0_______-505-0-0-505.jpg&amp;refer=http%3A%2F%2Fimg.jxdoc.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639322216&amp;t=88d1ea1adb9cbf1611eaf4c9fa16b8b0"
        title="img" /></p>
<p>如果嫌一个一个改太麻烦，也可以使用CD来快速创建不解析区域：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;test&gt;</span>
    <span class="nt">&lt;name&gt;</span><span class="cp">&lt;![CDATA[我看你&lt;&gt;&lt;&gt;&lt;&gt;是一点都不懂哦&gt;&gt;&gt;]]&gt;</span><span class="nt">&lt;/name&gt;</span>
<span class="nt">&lt;/test&gt;</span>
</code></pre></div><p>那么，我们现在了解了XML文件的定义，现在该如何去解析一个XML文件呢？比如我们希望将定义好的XML文件读取到Java程序中，这时该怎么做呢？</p>
<p>JDK为我们内置了一个叫做<code>org.w3c</code>的XML解析库，我们来看看如何使用它来进行XML文件内容解析：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">// 创建DocumentBuilderFactory对象
</span><span class="c1"></span><span class="n">DocumentBuilderFactory</span> <span class="n">factory</span> <span class="o">=</span> <span class="n">DocumentBuilderFactory</span><span class="o">.</span><span class="na">newInstance</span><span class="o">();</span>
<span class="c1">// 创建DocumentBuilder对象
</span><span class="c1"></span><span class="k">try</span> <span class="o">{</span>
    <span class="n">DocumentBuilder</span> <span class="n">builder</span> <span class="o">=</span> <span class="n">factory</span><span class="o">.</span><span class="na">newDocumentBuilder</span><span class="o">();</span>
    <span class="n">Document</span> <span class="n">d</span> <span class="o">=</span> <span class="n">builder</span><span class="o">.</span><span class="na">parse</span><span class="o">(</span><span class="s">&#34;file:mappers/test.xml&#34;</span><span class="o">);</span>
    <span class="c1">// 每一个标签都作为一个节点
</span><span class="c1"></span>    <span class="n">NodeList</span> <span class="n">nodeList</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="na">getElementsByTagName</span><span class="o">(</span><span class="s">&#34;test&#34;</span><span class="o">);</span>  <span class="c1">// 可能有很多个名字为test的标签
</span><span class="c1"></span>    <span class="n">Node</span> <span class="n">rootNode</span> <span class="o">=</span> <span class="n">nodeList</span><span class="o">.</span><span class="na">item</span><span class="o">(</span><span class="n">0</span><span class="o">);</span> <span class="c1">// 获取首个
</span><span class="c1"></span>
    <span class="n">NodeList</span> <span class="n">childNodes</span> <span class="o">=</span> <span class="n">rootNode</span><span class="o">.</span><span class="na">getChildNodes</span><span class="o">();</span> <span class="c1">// 一个节点下可能会有很多个节点，比如根节点下就囊括了所有的节点
</span><span class="c1"></span>    <span class="c1">//节点可以是一个带有内容的标签（它内部就还有子节点），也可以是一段文本内容
</span><span class="c1"></span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">childNodes</span><span class="o">.</span><span class="na">getLength</span><span class="o">();</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="n">Node</span> <span class="n">child</span> <span class="o">=</span> <span class="n">childNodes</span><span class="o">.</span><span class="na">item</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
        <span class="k">if</span><span class="o">(</span><span class="n">child</span><span class="o">.</span><span class="na">getNodeType</span><span class="o">()</span> <span class="o">==</span> <span class="n">Node</span><span class="o">.</span><span class="na">ELEMENT_NODE</span><span class="o">)</span>  <span class="c1">//过滤换行符之类的内容，因为它们都被认为是一个文本节点
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">child</span><span class="o">.</span><span class="na">getNodeName</span><span class="o">()</span> <span class="o">+</span> <span class="s">&#34;：&#34;</span> <span class="o">+</span><span class="n">child</span><span class="o">.</span><span class="na">getFirstChild</span><span class="o">().</span><span class="na">getNodeValue</span><span class="o">());</span>
        <span class="c1">// 输出节点名称，也就是标签名称，以及标签内部的文本（内部的内容都是子节点，所以要获取内部的节点）
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>当然，学习和使用XML只是为了更好地去认识Mybatis的工作原理，以及如何使用XML来作为Mybatis的配置文件，这是在开始之前必须要掌握的内容（使用Java读取XML内容不要求掌握，但是需要知道Mybatis就是通过这种方式来读取配置文件的）</p>
<p>不仅仅是Mybatis，包括后面的Spring等众多框架都会用到XML来作为框架的配置文件！</p>
<h3 id="初次使用mybatis">初次使用Mybatis</h3>
<p>那么我们首先来感受一下Mybatis给我们带来的便捷，就从搭建环境开始，中文文档网站：https://mybatis.org/mybatis-3/zh/configuration.html</p>
<p>我们需要导入Mybatis的依赖，Jar包需要在github上下载，如果卡得一匹，连不上可以在视频简介处从分享的文件中获取。同样地放入到项目的根目录下，右键作为依赖即可！（依赖变多之后，我们可以将其放到一个单独的文件夹，不然会很繁杂）</p>
<p>依赖导入完成后，我们就可以编写Mybatis的配置文件了（现在不是在Java代码中配置了，而是通过一个XML文件去配置，这样就使得硬编码的部分大大减少，项目后期打包成Jar运行不方便修复，但是通过配置文件，我们随时都可以去修改，就变得很方便了，同时代码量也大幅度减少，配置文件填写完成后，我们只需要关心项目的业务逻辑而不是如何去读取配置文件）我们按照官方文档给定的提示，在项目根目录下新建名为<code>mybatis-config.xml</code>的文件，并填写以下内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34; ?&gt;</span>
<span class="cp">&lt;!DOCTYPE configuration
</span><span class="cp">  PUBLIC &#34;-//mybatis.org//DTD Config 3.0//EN&#34;
</span><span class="cp">  &#34;http://mybatis.org/dtd/mybatis-3-config.dtd&#34;&gt;</span>
<span class="nt">&lt;configuration&gt;</span>
  <span class="nt">&lt;environments</span> <span class="na">default=</span><span class="s">&#34;development&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;environment</span> <span class="na">id=</span><span class="s">&#34;development&#34;</span><span class="nt">&gt;</span>
      <span class="nt">&lt;transactionManager</span> <span class="na">type=</span><span class="s">&#34;JDBC&#34;</span><span class="nt">/&gt;</span>
      <span class="nt">&lt;dataSource</span> <span class="na">type=</span><span class="s">&#34;POOLED&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;driver&#34;</span> <span class="na">value=</span><span class="s">&#34;${驱动类（含包名）}&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;url&#34;</span> <span class="na">value=</span><span class="s">&#34;${数据库连接URL}&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;username&#34;</span> <span class="na">value=</span><span class="s">&#34;${用户名}&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;password&#34;</span> <span class="na">value=</span><span class="s">&#34;${密码}&#34;</span><span class="nt">/&gt;</span>
      <span class="nt">&lt;/dataSource&gt;</span>
    <span class="nt">&lt;/environment&gt;</span>
  <span class="nt">&lt;/environments&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div><p>我们发现，在最上方还引入了一个叫做DTD（文档类型定义）的东西，它提前帮助我们规定了一些标签，我们就需要使用Mybatis提前帮助我们规定好的标签来进行配置（因为只有这样Mybatis才能正确识别我们配置的内容）</p>
<p>通过进行配置，我们就告诉了Mybatis我们链接数据库的一些信息，包括URL、用户名、密码等，这样Mybatis就知道该链接哪个数据库、使用哪个账号进行登陆了（也可以不使用配置文件，这里不做讲解，还请各位小伙伴自行阅读官方文档）</p>
<p>配置文件完成后，我们需要在Java程序启动时，让Mybatis对配置文件进行读取并得到一个<code>SqlSessionFactory</code>对象：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">FileNotFoundException</span> <span class="o">{</span>
    <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">().</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
			<span class="c1">//暂时还没有业务
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>直接运行即可，虽然没有干什么事情，但是不会出现错误，如果之前的配置文件编写错误，直接运行会产生报错！那么现在我们来看看，<code>SqlSessionFactory</code>对象是什么东西：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.h5w3.com%2Fwp-content%2Fuploads%2F2021%2F01%2F1460000039107464.png&amp;refer=http%3A%2F%2Fwww.h5w3.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639372889&amp;t=f37deb63f29f0dc2f8b6a3517a68b86c"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.h5w3.com%2Fwp-content%2Fuploads%2F2021%2F01%2F1460000039107464.png&amp;refer=http%3A%2F%2Fwww.h5w3.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639372889&amp;t=f37deb63f29f0dc2f8b6a3517a68b86c, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.h5w3.com%2Fwp-content%2Fuploads%2F2021%2F01%2F1460000039107464.png&amp;refer=http%3A%2F%2Fwww.h5w3.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639372889&amp;t=f37deb63f29f0dc2f8b6a3517a68b86c 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.h5w3.com%2Fwp-content%2Fuploads%2F2021%2F01%2F1460000039107464.png&amp;refer=http%3A%2F%2Fwww.h5w3.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639372889&amp;t=f37deb63f29f0dc2f8b6a3517a68b86c 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.h5w3.com%2Fwp-content%2Fuploads%2F2021%2F01%2F1460000039107464.png&amp;refer=http%3A%2F%2Fwww.h5w3.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639372889&amp;t=f37deb63f29f0dc2f8b6a3517a68b86c"
        title="img" /></p>
<p>每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的，我们可以通过<code>SqlSessionFactory</code>来创建多个新的会话，<code>SqlSession</code>对象，每个会话就相当于我不同的地方登陆一个账号去访问数据库，你也可以认为这就是之前JDBC中的<code>Statement</code>对象，会话之间相互隔离，没有任何关联。</p>
<p>而通过<code>SqlSession</code>就可以完成几乎所有的数据库操作，我们发现这个接口中定义了大量数据库操作的方法，因此，现在我们只需要通过一个对象就能完成数据库交互了，极大简化了之前的流程。</p>
<p>我们来尝试一下直接读取实体类，读取实体类肯定需要一个映射规则，比如类中的哪个字段对应数据库中的哪个字段，在查询语句返回结果后，Mybatis就会自动将对应的结果填入到对象的对应字段上。首先编写实体类，，直接使用Lombok是不是就很方便了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">lombok.Data</span><span class="o">;</span>

<span class="nd">@Data</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">sid</span><span class="o">;</span>   <span class="c1">//名称最好和数据库字段名称保持一致，不然可能会映射失败导致查询结果丢失
</span><span class="c1"></span>    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>在根目录下重新创建一个mapper文件夹，新建名为<code>TestMapper.xml</code>的文件作为我们的映射器，并填写以下内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34; ?&gt;</span>
<span class="cp">&lt;!DOCTYPE mapper
</span><span class="cp">        PUBLIC &#34;-//mybatis.org//DTD Mapper 3.0//EN&#34;
</span><span class="cp">        &#34;http://mybatis.org/dtd/mybatis-3-mapper.dtd&#34;&gt;</span>
<span class="nt">&lt;mapper</span> <span class="na">namespace=</span><span class="s">&#34;TestMapper&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;selectStudent&#34;</span> <span class="na">resultType=</span><span class="s">&#34;com.test.entity.Student&#34;</span><span class="nt">&gt;</span>
        select * from student
    <span class="nt">&lt;/select&gt;</span>
<span class="nt">&lt;/mapper&gt;</span>
</code></pre></div><p>其中namespace就是命名空间，每个Mapper都是唯一的，因此需要用一个命名空间来区分，它还可以用来绑定一个接口。我们在里面写入了一个select标签，表示添加一个select操作，同时id作为操作的名称，resultType指定为我们刚刚定义的实体类，表示将数据库结果映射为<code>Student</code>类，然后就在标签中写入我们的查询语句即可。</p>
<p>编写好后，我们在配置文件中添加这个Mapper映射器：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mappers&gt;</span>
    <span class="nt">&lt;mapper</span> <span class="na">url=</span><span class="s">&#34;file:mappers/TestMapper.xml&#34;</span><span class="nt">/&gt;</span>
    <span class="c">&lt;!--    这里用的是url，也可以使用其他类型，我们会在后面讲解    --&gt;</span>
<span class="nt">&lt;/mappers&gt;</span>
</code></pre></div><p>最后在程序中使用我们定义好的Mapper即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">FileNotFoundException</span> <span class="o">{</span>
    <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">().</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="n">student</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">selectList</span><span class="o">(</span><span class="s">&#34;selectStudent&#34;</span><span class="o">);</span>
        <span class="n">student</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们会发现，Mybatis非常智能，我们只需要告诉一个映射关系，就能够直接将查询结果转化为一个实体类！</p>
<h3 id="配置mybatis">配置Mybatis</h3>
<p>在了解了Mybatis为我们带来的便捷之后，现在我们就可以正式地去学习使用Mybatis了！</p>
<p>由于<code>SqlSessionFactory</code>一般只需要创建一次，因此我们可以创建一个工具类来集中创建<code>SqlSession</code>，这样会更加方便一些：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MybatisUtil</span> <span class="o">{</span>

    <span class="c1">//在类加载时就进行创建
</span><span class="c1"></span>    <span class="kd">private</span> <span class="kd">static</span> <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span><span class="o">;</span>
    <span class="kd">static</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">().</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 获取一个新的会话
</span><span class="cm">     * @param autoCommit 是否开启自动提交（跟JDBC是一样的，如果不自动提交，则会变成事务操作）
</span><span class="cm">     * @return SqlSession对象
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="n">SqlSession</span> <span class="nf">getSession</span><span class="o">(</span><span class="kt">boolean</span> <span class="n">autoCommit</span><span class="o">){</span>
        <span class="k">return</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="n">autoCommit</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在我们只需要在main方法中这样写即可查询结果了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="n">student</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">selectList</span><span class="o">(</span><span class="s">&#34;selectStudent&#34;</span><span class="o">);</span>
        <span class="n">student</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>之前我们演示了，如何创建一个映射器来将结果快速转换为实体类，但是这样可能还是不够方便，我们每次都需要去找映射器对应操作的名称，而且还要知道对应的返回类型，再通过<code>SqlSession</code>来执行对应的方法，能不能再方便一点呢？</p>
<p>现在，我们可以通过<code>namespace</code>来绑定到一个接口上，利用接口的特性，我们可以直接指明方法的行为，而实际实现则是由Mybatis来完成。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">TestMapper</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">selectStudent</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>将Mapper文件的命名空间修改为我们的接口，建议同时将其放到同名包中，作为内部资源：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mapper</span> <span class="na">namespace=</span><span class="s">&#34;com.test.mapper.TestMapper&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;selectStudent&#34;</span> <span class="na">resultType=</span><span class="s">&#34;com.test.entity.Student&#34;</span><span class="nt">&gt;</span>
        select * from student
    <span class="nt">&lt;/select&gt;</span>
<span class="nt">&lt;/mapper&gt;</span>
</code></pre></div><p>作为内部资源后，我们需要修改一下配置文件中的mapper定义，不使用url而是resource表示是Jar内部的文件：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mappers&gt;</span>
    <span class="nt">&lt;mapper</span> <span class="na">resource=</span><span class="s">&#34;com/test/mapper/TestMapper.xml&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/mappers&gt;</span>
</code></pre></div><p>现在我们就可以直接通过<code>SqlSession</code>获取对应的实现类，通过接口中定义的行为来直接获取结果：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="n">student</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">selectStudent</span><span class="o">();</span>
        <span class="n">student</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>那么肯定有人好奇，TestMapper明明是一个我们自己定义接口啊，Mybatis也不可能提前帮我们写了实现类啊，那这接口怎么就出现了一个实现类呢？我们可以通过调用<code>getClass()</code>方法来看看实现类是个什么：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">testMapper</span><span class="o">.</span><span class="na">getClass</span><span class="o">());</span>
</code></pre></div><p>我们发现，实现类名称很奇怪，名称为<code>com.sun.proxy.$Proxy4</code>，它是通过动态代理生成的，相当于动态生成了一个实现类，而不是预先定义好的，有关Mybatis这一部分的原理，我们放在最后一节进行讲解。</p>
<p>接下来，我们再来看配置文件，之前我们并没有对配置文件进行一个详细的介绍：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="o">&lt;</span><span class="n">configuration</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">environments</span> <span class="k">default</span><span class="o">=</span><span class="s">&#34;development&#34;</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">environment</span> <span class="n">id</span><span class="o">=</span><span class="s">&#34;development&#34;</span><span class="o">&gt;</span>
            <span class="o">&lt;</span><span class="n">transactionManager</span> <span class="n">type</span><span class="o">=</span><span class="s">&#34;JDBC&#34;</span><span class="o">/&gt;</span>
            <span class="o">&lt;</span><span class="n">dataSource</span> <span class="n">type</span><span class="o">=</span><span class="s">&#34;POOLED&#34;</span><span class="o">&gt;</span>
                <span class="o">&lt;</span><span class="n">property</span> <span class="n">name</span><span class="o">=</span><span class="s">&#34;driver&#34;</span> <span class="n">value</span><span class="o">=</span><span class="s">&#34;com.mysql.cj.jdbc.Driver&#34;</span><span class="o">/&gt;</span>
                <span class="o">&lt;</span><span class="n">property</span> <span class="n">name</span><span class="o">=</span><span class="s">&#34;url&#34;</span> <span class="n">value</span><span class="o">=</span><span class="s">&#34;jdbc:mysql://localhost:3306/study&#34;</span><span class="o">/&gt;</span>
                <span class="o">&lt;</span><span class="n">property</span> <span class="n">name</span><span class="o">=</span><span class="s">&#34;username&#34;</span> <span class="n">value</span><span class="o">=</span><span class="s">&#34;test&#34;</span><span class="o">/&gt;</span>
                <span class="o">&lt;</span><span class="n">property</span> <span class="n">name</span><span class="o">=</span><span class="s">&#34;password&#34;</span> <span class="n">value</span><span class="o">=</span><span class="s">&#34;123456&#34;</span><span class="o">/&gt;</span>
            <span class="o">&lt;/</span><span class="n">dataSource</span><span class="o">&gt;</span>
        <span class="o">&lt;/</span><span class="n">environment</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="n">environments</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">mappers</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">mapper</span> <span class="n">resource</span><span class="o">=</span><span class="s">&#34;com/test/mapper/TestMapper.xml&#34;</span><span class="o">/&gt;</span>
    <span class="o">&lt;/</span><span class="n">mappers</span><span class="o">&gt;</span>
<span class="o">&lt;/</span><span class="n">configuration</span><span class="o">&gt;</span>
</code></pre></div><p>首先就从<code>environments</code>标签说起，一般情况下，我们在开发中，都需要指定一个数据库的配置信息，包含连接URL、用户、密码等信息，而<code>environment</code>就是用于进行这些配置的！实际情况下可能会不止有一个数据库连接信息，比如开发过程中我们一般会使用本地的数据库，而如果需要将项目上传到服务器或是防止其他人的电脑上运行时，我们可能就需要配置另一个数据库的信息，因此，我们可以提前定义好所有的数据库信息，该什么时候用什么即可！</p>
<p>在<code>environments</code>标签上有一个default属性，来指定默认的环境，当然如果我们希望使用其他环境，可以修改这个默认环境，也可以在创建工厂时选择环境：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">()</span>
        <span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">),</span> <span class="s">&#34;环境ID&#34;</span><span class="o">);</span>
</code></pre></div><p>我们还可以给类型起一个别名，以简化Mapper的编写：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="o">&lt;!--</span> <span class="n">需要在environments的上方</span> <span class="o">--&gt;</span>
<span class="o">&lt;</span><span class="n">typeAliases</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">typeAlias</span> <span class="n">type</span><span class="o">=</span><span class="s">&#34;com.test.entity.Student&#34;</span> <span class="n">alias</span><span class="o">=</span><span class="s">&#34;Student&#34;</span><span class="o">/&gt;</span>
<span class="o">&lt;/</span><span class="n">typeAliases</span><span class="o">&gt;</span>
</code></pre></div><p>现在Mapper就可以直接使用别名了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mapper</span> <span class="na">namespace=</span><span class="s">&#34;com.test.mapper.TestMapper&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;selectStudent&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
        select * from student
    <span class="nt">&lt;/select&gt;</span>
<span class="nt">&lt;/mapper&gt;</span>
</code></pre></div><p>如果这样还是很麻烦，我们也可以直接让Mybatis去扫描一个包，并将包下的所有类自动起别名（别名为首字母小写的类名）</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="o">&lt;</span><span class="n">typeAliases</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="kn">package</span> <span class="nn">name</span><span class="o">=</span><span class="s">&#34;com.test.entity&#34;</span><span class="o">/&gt;</span>
<span class="o">&lt;/</span><span class="n">typeAliases</span><span class="o">&gt;</span>
</code></pre></div><p>也可以为指定实体类添加一个注解，来指定别名：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="nd">@Alias</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>当然，Mybatis也包含许多的基础配置，通过使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;settings&gt;</span>
    <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;&#34;</span> <span class="na">value=</span><span class="s">&#34;&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/settings&gt;</span>
</code></pre></div><p>所有的配置项可以在中文文档处查询，本文不会进行详细介绍，在后面我们会提出一些比较重要的配置项。</p>
<p>有关配置文件的介绍就暂时到这里为止，我们讨论的重心应该是Mybatis的应用，而不是配置文件，所以省略了一部分内容的讲解。</p>
<h3 id="增删改查">增删改查</h3>
<p>在了解了Mybatis的一些基本配置之后，我们就可以正式来使用Mybatis来进行数据库操作了！</p>
<p>在前面我们演示了如何快速进行查询，我们只需要编写一个对应的映射器既可以了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mapper</span> <span class="na">namespace=</span><span class="s">&#34;com.test.mapper.TestMapper&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;studentList&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
        select * from student
    <span class="nt">&lt;/select&gt;</span>
<span class="nt">&lt;/mapper&gt;</span>
</code></pre></div><p>当然，如果你不喜欢使用实体类，那么这些属性还可以被映射到一个Map上：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;selectStudent&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Map&#34;</span><span class="nt">&gt;</span>
    select * from student
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">TestMapper</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Map</span><span class="o">&gt;</span> <span class="nf">selectStudent</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>Map中就会以键值对的形式来存放这些结果了。</p>
<p>通过设定一个<code>resultType</code>属性，让Mybatis知道查询结果需要映射为哪个实体类，要求字段名称保持一致。那么如果我们不希望按照这样的规则来映射呢？我们可以自定义<code>resultMap</code>来设定映射规则：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;Test&#34;</span> <span class="na">type=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span> <span class="na">property=</span><span class="s">&#34;sid&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sex&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">property=</span><span class="s">&#34;sex&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
</code></pre></div><p>通过指定映射规则，我们现在名称和性别一栏就发生了交换，因为我们将其映射字段进行了交换。</p>
<p>如果一个类中存在多个构造方法，那么很有可能会出现这样的错误：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="err">###</span> <span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">exceptions</span><span class="o">.</span><span class="na">PersistenceException</span><span class="o">:</span> 
<span class="err">###</span> <span class="n">Error</span> <span class="n">querying</span> <span class="n">database</span><span class="o">.</span>  <span class="n">Cause</span><span class="o">:</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">executor</span><span class="o">.</span><span class="na">ExecutorException</span><span class="o">:</span> <span class="n">No</span> <span class="n">constructor</span> <span class="n">found</span> <span class="n">in</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">entity</span><span class="o">.</span><span class="na">Student</span> <span class="n">matching</span> <span class="o">[</span><span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">Integer</span><span class="o">,</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">,</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">]</span>
<span class="err">###</span> <span class="n">The</span> <span class="n">error</span> <span class="n">may</span> <span class="n">exist</span> <span class="n">in</span> <span class="n">com</span><span class="o">/</span><span class="n">test</span><span class="o">/</span><span class="n">mapper</span><span class="o">/</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">xml</span>
<span class="err">###</span> <span class="n">The</span> <span class="n">error</span> <span class="n">may</span> <span class="n">involve</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">mapper</span><span class="o">.</span><span class="na">TestMapper</span><span class="o">.</span><span class="na">getStudentBySid</span>
<span class="err">###</span> <span class="n">The</span> <span class="n">error</span> <span class="n">occurred</span> <span class="k">while</span> <span class="n">handling</span> <span class="n">results</span>
<span class="err">###</span> <span class="n">SQL</span><span class="o">:</span> <span class="n">select</span> <span class="o">*</span> <span class="n">from</span> <span class="n">student</span> <span class="n">where</span> <span class="n">sid</span> <span class="o">=</span> <span class="o">?</span>
<span class="err">###</span> <span class="n">Cause</span><span class="o">:</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">executor</span><span class="o">.</span><span class="na">ExecutorException</span><span class="o">:</span> <span class="n">No</span> <span class="n">constructor</span> <span class="n">found</span> <span class="n">in</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">entity</span><span class="o">.</span><span class="na">Student</span> <span class="n">matching</span> <span class="o">[</span><span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">Integer</span><span class="o">,</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">,</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">]</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">exceptions</span><span class="o">.</span><span class="na">ExceptionFactory</span><span class="o">.</span><span class="na">wrapException</span><span class="o">(</span><span class="n">ExceptionFactory</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">30</span><span class="o">)</span>
	<span class="o">...</span>
</code></pre></div><p>这时就需要使用<code>constructor</code>标签来指定构造方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;test&#34;</span> <span class="na">type=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;constructor&gt;</span>
        <span class="nt">&lt;arg</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span> <span class="na">javaType=</span><span class="s">&#34;Integer&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;arg</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">javaType=</span><span class="s">&#34;String&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/constructor&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
</code></pre></div><p>值得注意的是，指定构造方法后，若此字段被填入了构造方法作为参数，将不会通过反射给字段单独赋值，而构造方法中没有传入的字段，依然会被反射赋值，有关<code>resultMap</code>的内容，后面还会继续讲解。</p>
<p>如果数据库中存在一个带下划线的字段，我们可以通过设置让其映射为以驼峰命名的字段，比如<code>my_test</code>映射为<code>myTest</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;settings&gt;</span>
    <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;mapUnderscoreToCamelCase&#34;</span> <span class="na">value=</span><span class="s">&#34;true&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/settings&gt;</span>
</code></pre></div><p>如果不设置，默认为不开启，也就是默认需要名称保持一致。</p>
<p>我们接着来看看条件查询，既然是条件查询，那么肯定需要我们传入查询条件，比如现在我们想通过sid字段来通过学号查找信息：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Student</span> <span class="nf">getStudentBySid</span><span class="o">(</span><span class="kt">int</span> <span class="n">sid</span><span class="o">);</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;getStudentBySid&#34;</span> <span class="na">parameterType=</span><span class="s">&#34;int&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    select * from student where sid = #{sid}
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><p>我们通过使用<code>#{xxx}</code>或是<code>${xxx}</code>来填入我们给定的属性，实际上Mybatis本质也是通过<code>PreparedStatement</code>首先进行一次预编译，有效地防止SQL注入问题，但是如果使用<code>${xxx}</code>就不再是通过预编译，而是直接传值，因此我们一般都使用<code>#{xxx}</code>来进行操作。</p>
<p>使用<code>parameterType</code>属性来指定参数类型（非必须，可以不用，推荐不用）</p>
<p>接着我们来看插入、更新和删除操作，其实与查询操作差不多，不过需要使用对应的标签，比如插入操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;insert</span> <span class="na">id=</span><span class="s">&#34;addStudent&#34;</span> <span class="na">parameterType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    insert into student(name, sex) values(#{name}, #{sex})
<span class="nt">&lt;/insert&gt;</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span> <span class="nf">addStudent</span><span class="o">(</span><span class="n">Student</span> <span class="n">student</span><span class="o">);</span>
</code></pre></div><p>我们这里使用的是一个实体类，我们可以直接使用实体类里面对应属性替换到SQL语句中，只需要填写属性名称即可，和条件查询是一样的。</p>
<h3 id="复杂查询">复杂查询</h3>
<p>一个老师可以教授多个学生，那么能否一次性将老师的学生全部映射给此老师的对象呢，比如：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Teacher</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">tid</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="n">studentList</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>映射为Teacher对象时，同时将其教授的所有学生一并映射为List列表，显然这是一种一对多的查询，那么这时就需要进行复杂查询了。而我们之前编写的都非常简单，直接就能完成映射，因此我们现在需要使用<code>resultMap</code>来自定义映射规则：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;getTeacherByTid&#34;</span> <span class="na">resultMap=</span><span class="s">&#34;asTeacher&#34;</span><span class="nt">&gt;</span>
        select *, teacher.name as tname from student inner join teach on student.sid = teach.sid
                              inner join teacher on teach.tid = teacher.tid where teach.tid = #{tid}
<span class="nt">&lt;/select&gt;</span>

<span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;asTeacher&#34;</span> <span class="na">type=</span><span class="s">&#34;Teacher&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;id</span> <span class="na">column=</span><span class="s">&#34;tid&#34;</span> <span class="na">property=</span><span class="s">&#34;tid&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;tname&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;collection</span> <span class="na">property=</span><span class="s">&#34;studentList&#34;</span> <span class="na">ofType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;id</span> <span class="na">property=</span><span class="s">&#34;sid&#34;</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sex&#34;</span> <span class="na">property=</span><span class="s">&#34;sex&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/collection&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
</code></pre></div><p>可以看到，我们的查询结果是一个多表联查的结果，而联查的数据就是我们需要映射的数据（比如这里是一个老师有N个学生，联查的结果也是这一个老师对应N个学生的N条记录），其中<code>id</code>标签用于在多条记录中辨别是否为同一个对象的数据，比如上面的查询语句得到的结果中，<code>tid</code>这一行始终为<code>1</code>，因此所有的记录都应该是<code>tid=1</code>的教师的数据，而不应该变为多个教师的数据，如果不加id进行约束，那么会被识别成多个教师的数据！</p>
<p>通过使用collection来表示将得到的所有结果合并为一个集合，比如上面的数据中每个学生都有单独的一条记录，因此tid相同的全部学生的记录就可以最后合并为一个List，得到最终的映射结果，当然，为了区分，最好也设置一个id，只不过这个例子中可以当做普通的<code>result</code>使用。</p>
<p>了解了一对多，那么多对一又该如何查询呢，比如每个学生都有一个对应的老师，现在Student新增了一个Teacher对象，那么现在又该如何去处理呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="nd">@Accessors</span><span class="o">(</span><span class="n">chain</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">Teacher</span> <span class="n">teacher</span><span class="o">;</span>
<span class="o">}</span>

<span class="nd">@Data</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Teacher</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">tid</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>现在我们希望的是，每次查询到一个Student对象时都带上它的老师，同样的，我们也可以使用<code>resultMap</code>来实现（先修改一下老师的类定义，不然会很麻烦）：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;test2&#34;</span> <span class="na">type=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;id</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span> <span class="na">property=</span><span class="s">&#34;sid&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sex&#34;</span> <span class="na">property=</span><span class="s">&#34;sex&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;association</span> <span class="na">property=</span><span class="s">&#34;teacher&#34;</span> <span class="na">javaType=</span><span class="s">&#34;Teacher&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;id</span> <span class="na">column=</span><span class="s">&#34;tid&#34;</span> <span class="na">property=</span><span class="s">&#34;tid&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;tname&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/association&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
<span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;selectStudent&#34;</span> <span class="na">resultMap=</span><span class="s">&#34;test2&#34;</span><span class="nt">&gt;</span>
    select *, teacher.name as tname from student left join teach on student.sid = teach.sid
                                                 left join teacher on teach.tid = teacher.tid
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><p>通过使用<code>association</code>进行关联，形成多对一的关系，实际上和一对多是同理的，都是对查询结果的一种处理方式罢了。</p>
<h3 id="事务操作">事务操作</h3>
<p>我们可以在获取<code>SqlSession</code>关闭自动提交来开启事务模式，和JDBC其实都差不多：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">false</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

        <span class="n">testMapper</span><span class="o">.</span><span class="na">addStudent</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小王&#34;</span><span class="o">));</span>

        <span class="n">testMapper</span><span class="o">.</span><span class="na">selectStudent</span><span class="o">().</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，在关闭自动提交后，我们的内容是没有进入到数据库的，现在我们来试一下在最后提交事务：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">sqlSession</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>
</code></pre></div><p>在事务提交后，我们的内容才会被写入到数据库中。现在我们来试试看回滚操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">false</span><span class="o">)){</span>
    <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

    <span class="n">testMapper</span><span class="o">.</span><span class="na">addStudent</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小王&#34;</span><span class="o">));</span>

    <span class="n">testMapper</span><span class="o">.</span><span class="na">selectStudent</span><span class="o">().</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
    <span class="n">sqlSession</span><span class="o">.</span><span class="na">rollback</span><span class="o">();</span>
    <span class="n">sqlSession</span><span class="o">.</span><span class="na">commit</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>回滚操作也印证成功。</p>
<h3 id="动态sql">动态SQL</h3>
<p>动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架，你应该能理解根据不同条件拼接 SQL 语句有多痛苦，例如拼接时要确保不能忘记添加必要的空格，还要注意去掉列表最后一个列名的逗号。利用动态 SQL，可以彻底摆脱这种痛苦。</p>
<p>我们直接使用官网的例子进行讲解。</p>
<h3 id="缓存机制">缓存机制</h3>
<p>MyBatis 内置了一个强大的事务性查询缓存机制，它可以非常方便地配置和定制。</p>
<p>其实缓存机制我们在之前学习IO流的时候已经提及过了，我们可以提前将一部分内容放入缓存，下次需要获取数据时，我们就可以直接从缓存中读取，这样的话相当于直接从内存中获取而不是再去向数据库索要数据，效率会更高。</p>
<p>因此Mybatis内置了一个缓存机制，我们查询时，如果缓存中存在数据，那么我们就可以直接从缓存中获取，而不是再去向数据库进行请求。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fresource.shangmayuan.com%2Fdroxy-blog%2F2021%2F03%2F02%2F071d25e4f9d841e0ac9df54038d98fd0-2.png&amp;refer=http%3A%2F%2Fresource.shangmayuan.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639463836&amp;t=38cf5a85386f76cfd22ca3c6dcc5b6bb"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fresource.shangmayuan.com%2Fdroxy-blog%2F2021%2F03%2F02%2F071d25e4f9d841e0ac9df54038d98fd0-2.png&amp;refer=http%3A%2F%2Fresource.shangmayuan.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639463836&amp;t=38cf5a85386f76cfd22ca3c6dcc5b6bb, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fresource.shangmayuan.com%2Fdroxy-blog%2F2021%2F03%2F02%2F071d25e4f9d841e0ac9df54038d98fd0-2.png&amp;refer=http%3A%2F%2Fresource.shangmayuan.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639463836&amp;t=38cf5a85386f76cfd22ca3c6dcc5b6bb 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fresource.shangmayuan.com%2Fdroxy-blog%2F2021%2F03%2F02%2F071d25e4f9d841e0ac9df54038d98fd0-2.png&amp;refer=http%3A%2F%2Fresource.shangmayuan.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639463836&amp;t=38cf5a85386f76cfd22ca3c6dcc5b6bb 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fresource.shangmayuan.com%2Fdroxy-blog%2F2021%2F03%2F02%2F071d25e4f9d841e0ac9df54038d98fd0-2.png&amp;refer=http%3A%2F%2Fresource.shangmayuan.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639463836&amp;t=38cf5a85386f76cfd22ca3c6dcc5b6bb"
        title="img" /></p>
<p>Mybatis存在一级缓存和二级缓存，我们首先来看一下一级缓存，默认情况下，只启用了本地的会话缓存，它仅仅对一个会话中的数据进行缓存（一级缓存无法关闭，只能调整），我们来看看下面这段代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">InterruptedException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">Student</span> <span class="n">student1</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">Student</span> <span class="n">student2</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student1</span> <span class="o">==</span> <span class="n">student2</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，两次得到的是同一个Student对象，也就是说我们第二次查询并没有重新去构造对象，而是直接得到之前创建好的对象。如果还不是很明显，我们可以修改一下实体类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="nd">@Accessors</span><span class="o">(</span><span class="n">chain</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我被构造了&#34;</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>我们通过前面的学习得知Mybatis在映射为对象时，在只有一个构造方法的情况下，无论你构造方法写成什么样子，都会去调用一次构造方法，如果存在多个构造方法，那么就会去找匹配的构造方法。我们可以通过查看构造方法来验证对象被创建了几次。</p>
<p>结果显而易见，只创建了一次，也就是说当第二次进行同样的查询时，会直接使用第一次的结果，因为第一次的结果已经被缓存了。</p>
<p>那么如果我修改了数据库中的内容，缓存还会生效吗：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">InterruptedException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">Student</span> <span class="n">student1</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">testMapper</span><span class="o">.</span><span class="na">addStudent</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小李&#34;</span><span class="o">).</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">));</span>
        <span class="n">Student</span> <span class="n">student2</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student1</span> <span class="o">==</span> <span class="n">student2</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，当我们进行了插入操作后，缓存就没有生效了，我们再次进行查询得到的是一个新创建的对象。</p>
<p>也就是说，一级缓存，在进行DML操作后，会使得缓存失效，也就是说Mybatis知道我们对数据库里面的数据进行了修改，所以之前缓存的内容可能就不是当前数据库里面最新的内容了。还有一种情况就是，当前会话结束后，也会清理全部的缓存，因为已经不会再用到了。但是一定注意，一级缓存只针对于单个会话，多个会话之间不相通。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

        <span class="n">Student</span> <span class="n">student2</span><span class="o">;</span>
        <span class="k">try</span><span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession2</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">testMapper2</span> <span class="o">=</span> <span class="n">sqlSession2</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">student2</span> <span class="o">=</span> <span class="n">testMapper2</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="o">}</span>

        <span class="n">Student</span> <span class="n">student1</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student1</span> <span class="o">==</span> <span class="n">student2</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>**注意：**一个会话DML操作只会重置当前会话的缓存，不会重置其他会话的缓存，也就是说，其他会话缓存是不会更新的！</p>
<p>一级缓存给我们提供了很高速的访问效率，但是它的作用范围实在是有限，如果一个会话结束，那么之前的缓存就全部失效了，但是我们希望缓存能够扩展到所有会话都能使用，因此我们可以通过二级缓存来实现，二级缓存默认是关闭状态，要开启二级缓存，我们需要在映射器XML文件中添加：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;cache/&gt;</span>
</code></pre></div><p>可见二级缓存是Mapper级别的，也就是说，当一个会话失效时，它的缓存依然会存在于二级缓存中，因此如果我们再次创建一个新的会话会直接使用之前的缓存，我们首先根据官方文档进行一些配置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;cache</span>
  <span class="na">eviction=</span><span class="s">&#34;FIFO&#34;</span>
  <span class="na">flushInterval=</span><span class="s">&#34;60000&#34;</span>
  <span class="na">size=</span><span class="s">&#34;512&#34;</span>
  <span class="na">readOnly=</span><span class="s">&#34;true&#34;</span><span class="nt">/&gt;</span>
</code></pre></div><p>我们来编写一个代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Student</span> <span class="n">student</span><span class="o">;</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">student</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession2</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper2</span> <span class="o">=</span> <span class="n">sqlSession2</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">Student</span> <span class="n">student2</span> <span class="o">=</span> <span class="n">testMapper2</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student2</span> <span class="o">==</span> <span class="n">student</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们可以看到，上面的代码中首先是第一个会话在进行读操作，完成后会结束会话，而第二个操作重新创建了一个新的会话，再次执行了同样的查询，我们发现得到的依然是缓存的结果。</p>
<p>那么如果我不希望某个方法开启缓存呢？我们可以添加useCache属性来关闭缓存：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;getStudentBySid&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span> <span class="na">useCache=</span><span class="s">&#34;false&#34;</span><span class="nt">&gt;</span>
    select * from student where sid = #{sid}
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><p>我们也可以使用flushCache=&ldquo;false&quot;在每次执行后都清空缓存，通过这这个我们还可以控制DML操作完成之后不清空缓存。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;getStudentBySid&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span> <span class="na">flushCache=</span><span class="s">&#34;true&#34;</span><span class="nt">&gt;</span>
    select * from student where sid = #{sid}
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><p>添加了二级缓存之后，会先从二级缓存中查找数据，当二级缓存中没有时，才会从一级缓存中获取，当一级缓存中都还没有数据时，才会请求数据库，因此我们再来执行上面的代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

        <span class="n">Student</span> <span class="n">student2</span><span class="o">;</span>
        <span class="k">try</span><span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession2</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">testMapper2</span> <span class="o">=</span> <span class="n">sqlSession2</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">student2</span> <span class="o">=</span> <span class="n">testMapper2</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="o">}</span>

        <span class="n">Student</span> <span class="n">student1</span> <span class="o">=</span> <span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student1</span> <span class="o">==</span> <span class="n">student2</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>得到的结果就会是同一个对象了，因为现在是优先从二级缓存中获取。</p>
<p>读取顺序：二级缓存 =&gt; 一级缓存 =&gt; 数据库</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F2176079-2e6599c454e7af19.png&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639471352&amp;t=c7c1d6b11de1ad9af91e092590c58d83"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F2176079-2e6599c454e7af19.png&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639471352&amp;t=c7c1d6b11de1ad9af91e092590c58d83, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F2176079-2e6599c454e7af19.png&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639471352&amp;t=c7c1d6b11de1ad9af91e092590c58d83 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F2176079-2e6599c454e7af19.png&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639471352&amp;t=c7c1d6b11de1ad9af91e092590c58d83 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F2176079-2e6599c454e7af19.png&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639471352&amp;t=c7c1d6b11de1ad9af91e092590c58d83"
        title="img" /></p>
<p>虽然缓存机制给我们提供了很大的性能提升，但是缓存存在一个问题，我们之前在<code>计算机组成原理</code>中可能学习过缓存一致性问题，也就是说当多个CPU在操作自己的缓存时，可能会出现各自的缓存内容不同步的问题，而Mybatis也会这样，我们来看看这个例子：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">InterruptedException</span> <span class="o">{</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">){</span>
            <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">3000</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">));</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们现在循环地每三秒读取一次，而在这个过程中，我们使用IDEA手动修改数据库中的数据，将1号同学的学号改成100，那么理想情况下，下一次读取将无法获取到小明，因为小明的学号已经发生变化了。</p>
<p>但是结果却是依然能够读取，并且sid并没有发生改变，这也证明了Mybatis的缓存在生效，因为我们是从外部进行修改，Mybatis不知道我们修改了数据，所以依然在使用缓存中的数据，但是这样很明显是不正确的，因此，如果存在多台服务器或者是多个程序都在使用Mybatis操作同一个数据库，并且都开启了缓存，需要解决这个问题，要么就得关闭Mybatis的缓存来保证一致性：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;settings&gt;</span>
    <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;cacheEnabled&#34;</span> <span class="na">value=</span><span class="s">&#34;false&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/settings&gt;</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;select</span> <span class="na">id=</span><span class="s">&#34;getStudentBySid&#34;</span> <span class="na">resultType=</span><span class="s">&#34;Student&#34;</span> <span class="na">useCache=</span><span class="s">&#34;false&#34;</span> <span class="na">flushCache=</span><span class="s">&#34;true&#34;</span><span class="nt">&gt;</span>
    select * from student where sid = #{sid}
<span class="nt">&lt;/select&gt;</span>
</code></pre></div><p>要么就需要实现缓存共用，也就是让所有的Mybatis都使用同一个缓存进行数据存取，在后面，我们会继续学习Redis、Ehcache、Memcache等缓存框架，通过使用这些工具，就能够很好地解决缓存一致性问题。</p>
<h3 id="使用注解开发">使用注解开发</h3>
<p>在之前的开发中，我们已经体验到Mybatis为我们带来的便捷了，我们只需要编写对应的映射器，并将其绑定到一个接口上，即可直接通过该接口执行我们的SQL语句，极大的简化了我们之前JDBC那样的代码编写模式。那么，能否实现无需xml映射器配置，而是直接使用注解在接口上进行配置呢？答案是可以的，也是现在推荐的一种方式（也不是说XML就不要去用了，由于Java 注解的表达能力和灵活性十分有限，可能相对于XML配置某些功能实现起来会不太好办，但是在大部分场景下，直接使用注解开发已经绰绰有余了）</p>
<p>首先我们来看一下，使用XML进行映射器编写时，我们需要现在XML中定义映射规则和SQL语句，然后再将其绑定到一个接口的方法定义上，然后再使用接口来执行：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;insert</span> <span class="na">id=</span><span class="s">&#34;addStudent&#34;</span><span class="nt">&gt;</span>
    insert into student(name, sex) values(#{name}, #{sex})
<span class="nt">&lt;/insert&gt;</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span> <span class="nf">addStudent</span><span class="o">(</span><span class="n">Student</span> <span class="n">student</span><span class="o">);</span>
</code></pre></div><p>而现在，我们可以直接使用注解来实现，每个操作都有一个对应的注解：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Insert</span><span class="o">(</span><span class="s">&#34;insert into student(name, sex) values(#{name}, #{sex})&#34;</span><span class="o">)</span>
<span class="kt">int</span> <span class="nf">addStudent</span><span class="o">(</span><span class="n">Student</span> <span class="n">student</span><span class="o">);</span>
</code></pre></div><p>当然，我们还需要修改一下配置文件中的映射器注册：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="o">&lt;</span><span class="n">mappers</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">mapper</span> <span class="n">class</span><span class="o">=</span><span class="s">&#34;com.test.mapper.MyMapper&#34;</span><span class="o">/&gt;</span>
    <span class="o">&lt;!--</span>  <span class="n">也可以直接注册整个包下的</span> <span class="o">&lt;</span><span class="kn">package</span> <span class="nn">name</span><span class="o">=</span><span class="s">&#34;com.test.mapper&#34;</span><span class="o">/&gt;</span>  <span class="o">--&gt;</span>
<span class="o">&lt;/</span><span class="n">mappers</span><span class="o">&gt;</span>
</code></pre></div><p>通过直接指定Class，来让Mybatis知道我们这里有一个通过注解实现的映射器。</p>
<p>我们接着来看一下，如何使用注解进行自定义映射规则：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Results</span><span class="o">({</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">id</span> <span class="o">=</span> <span class="kc">true</span><span class="o">,</span> <span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sex&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;sex&#34;</span><span class="o">)</span>
<span class="o">})</span>
<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student&#34;</span><span class="o">)</span>
<span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">getAllStudent</span><span class="o">();</span>
</code></pre></div><p>直接通过<code>@Results</code>注解，就可以直接进行配置了，此注解的value是一个<code>@Result</code>注解数组，每个<code>@Result</code>注解都都一个单独的字段配置，其实就是我们之前在XML映射器中写的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;test&#34;</span> <span class="na">type=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;id</span> <span class="na">property=</span><span class="s">&#34;sid&#34;</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">property=</span><span class="s">&#34;sex&#34;</span><span class="nt">/&gt;</span>    
  	<span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sex&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
</code></pre></div><p>现在我们就可以通过注解来自定义映射规则了。那么如何使用注解来完成复杂查询呢？我们还是使用一个老师多个学生的例子：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Results</span><span class="o">({</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">id</span> <span class="o">=</span> <span class="kc">true</span><span class="o">,</span> <span class="n">column</span> <span class="o">=</span> <span class="s">&#34;tid&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;tid&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;tid&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;studentList&#34;</span><span class="o">,</span> <span class="n">many</span> <span class="o">=</span>
            <span class="nd">@Many</span><span class="o">(</span><span class="n">select</span> <span class="o">=</span> <span class="s">&#34;getStudentByTid&#34;</span><span class="o">)</span>
        <span class="o">)</span>
<span class="o">})</span>
<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from teacher where tid = #{tid}&#34;</span><span class="o">)</span>
<span class="n">Teacher</span> <span class="nf">getTeacherBySid</span><span class="o">(</span><span class="kt">int</span> <span class="n">tid</span><span class="o">);</span>

<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student inner join teach on student.sid = teach.sid where tid = #{tid}&#34;</span><span class="o">)</span>
<span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">getStudentByTid</span><span class="o">(</span><span class="kt">int</span> <span class="n">tid</span><span class="o">);</span>
</code></pre></div><p>我们发现，多出了一个子查询，而这个子查询是单独查询该老师所属学生的信息，而子查询结果作为<code>@Result</code>注解的一个many结果，代表子查询的所有结果都归入此集合中（也就是之前的collection标签）</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;resultMap</span> <span class="na">id=</span><span class="s">&#34;asTeacher&#34;</span> <span class="na">type=</span><span class="s">&#34;Teacher&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;id</span> <span class="na">column=</span><span class="s">&#34;tid&#34;</span> <span class="na">property=</span><span class="s">&#34;tid&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;tname&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;collection</span> <span class="na">property=</span><span class="s">&#34;studentList&#34;</span> <span class="na">ofType=</span><span class="s">&#34;Student&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;id</span> <span class="na">property=</span><span class="s">&#34;sid&#34;</span> <span class="na">column=</span><span class="s">&#34;sid&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;name&#34;</span> <span class="na">property=</span><span class="s">&#34;name&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;result</span> <span class="na">column=</span><span class="s">&#34;sex&#34;</span> <span class="na">property=</span><span class="s">&#34;sex&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/collection&gt;</span>
<span class="nt">&lt;/resultMap&gt;</span>
</code></pre></div><p>同理，<code>@Result</code>也提供了<code>@One</code>子注解来实现一对一的关系表示，类似于之前的<code>assocation</code>标签：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Results</span><span class="o">({</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">id</span> <span class="o">=</span> <span class="kc">true</span><span class="o">,</span> <span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sex&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;sex&#34;</span><span class="o">),</span>
        <span class="nd">@Result</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">,</span> <span class="n">property</span> <span class="o">=</span> <span class="s">&#34;teacher&#34;</span><span class="o">,</span> <span class="n">one</span> <span class="o">=</span>
            <span class="nd">@One</span><span class="o">(</span><span class="n">select</span> <span class="o">=</span> <span class="s">&#34;getTeacherBySid&#34;</span><span class="o">)</span>
        <span class="o">)</span>
<span class="o">})</span>
<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student&#34;</span><span class="o">)</span>
<span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">getAllStudent</span><span class="o">();</span>
</code></pre></div><p>如果现在我希望直接使用注解编写SQL语句但是我希望映射规则依然使用XML来实现，这时该怎么办呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@ResultMap</span><span class="o">(</span><span class="s">&#34;test&#34;</span><span class="o">)</span>
<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student&#34;</span><span class="o">)</span>
<span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">getAllStudent</span><span class="o">();</span>
</code></pre></div><p>提供了<code>@ResultMap</code>注解，直接指定ID即可，这样我们就可以使用XML中编写的映射规则了，这里就不再演示了。</p>
<p>那么如果出现之前的两个构造方法的情况，且没有任何一个构造方法匹配的话，该怎么处理呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="nd">@Accessors</span><span class="o">(</span><span class="n">chain</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(</span><span class="kt">int</span> <span class="n">sid</span><span class="o">){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我是一号构造方法&#34;</span><span class="o">+</span><span class="n">sid</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(</span><span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="n">String</span> <span class="n">name</span><span class="o">){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我是二号构造方法&#34;</span><span class="o">+</span><span class="n">sid</span><span class="o">+</span><span class="n">name</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">sex</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>我们可以通过<code>@ConstructorArgs</code>注解来指定构造方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@ConstructorArgs</span><span class="o">({</span>
        <span class="nd">@Arg</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;sid&#34;</span><span class="o">,</span> <span class="n">javaType</span> <span class="o">=</span> <span class="kt">int</span><span class="o">.</span><span class="na">class</span><span class="o">),</span>
        <span class="nd">@Arg</span><span class="o">(</span><span class="n">column</span> <span class="o">=</span> <span class="s">&#34;name&#34;</span><span class="o">,</span> <span class="n">javaType</span> <span class="o">=</span> <span class="n">String</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
<span class="o">})</span>
<span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student where sid = #{sid} and sex = #{sex}&#34;</span><span class="o">)</span>
<span class="n">Student</span> <span class="nf">getStudentBySidAndSex</span><span class="o">(</span><span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sid&#34;</span><span class="o">)</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sex&#34;</span><span class="o">)</span> <span class="n">String</span> <span class="n">sex</span><span class="o">);</span>
</code></pre></div><p>得到的结果和使用<code>constructor</code>标签效果一致，这里就不多做讲解了。</p>
<p>我们发现，当参数列表中出现两个以上的参数时，会出现错误：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student where sid = #{sid} and sex = #{sex}&#34;</span><span class="o">)</span>
<span class="n">Student</span> <span class="nf">getStudentBySidAndSex</span><span class="o">(</span><span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="n">String</span> <span class="n">sex</span><span class="o">);</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">exceptions</span><span class="o">.</span><span class="na">PersistenceException</span><span class="o">:</span> 
<span class="err">###</span> <span class="n">Error</span> <span class="n">querying</span> <span class="n">database</span><span class="o">.</span>  <span class="n">Cause</span><span class="o">:</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">BindingException</span><span class="o">:</span> <span class="n">Parameter</span> <span class="err">&#39;</span><span class="n">sid</span><span class="err">&#39;</span> <span class="n">not</span> <span class="n">found</span><span class="o">.</span> <span class="n">Available</span> <span class="n">parameters</span> <span class="n">are</span> <span class="o">[</span><span class="n">arg1</span><span class="o">,</span> <span class="n">arg0</span><span class="o">,</span> <span class="n">param1</span><span class="o">,</span> <span class="n">param2</span><span class="o">]</span>
<span class="err">###</span> <span class="n">Cause</span><span class="o">:</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">BindingException</span><span class="o">:</span> <span class="n">Parameter</span> <span class="err">&#39;</span><span class="n">sid</span><span class="err">&#39;</span> <span class="n">not</span> <span class="n">found</span><span class="o">.</span> <span class="n">Available</span> <span class="n">parameters</span> <span class="n">are</span> <span class="o">[</span><span class="n">arg1</span><span class="o">,</span> <span class="n">arg0</span><span class="o">,</span> <span class="n">param1</span><span class="o">,</span> <span class="n">param2</span><span class="o">]</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">exceptions</span><span class="o">.</span><span class="na">ExceptionFactory</span><span class="o">.</span><span class="na">wrapException</span><span class="o">(</span><span class="n">ExceptionFactory</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">30</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">selectList</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">153</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">selectList</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">145</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">selectList</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">140</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">selectOne</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">76</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperMethod</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="n">MapperMethod</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">87</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperProxy$PlainMethodInvoker</span><span class="o">.</span><span class="na">invoke</span><span class="o">(</span><span class="n">MapperProxy</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">145</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperProxy</span><span class="o">.</span><span class="na">invoke</span><span class="o">(</span><span class="n">MapperProxy</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">86</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">sun</span><span class="o">.</span><span class="na">proxy</span><span class="o">.</span><span class="na">$Proxy6</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">Unknown</span> <span class="n">Source</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">16</span><span class="o">)</span>
</code></pre></div><p>原因是Mybatis不明确到底哪个参数是什么，因此我们可以添加<code>@Param</code>来指定参数名称：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student where sid = #{sid} and sex = #{sex}&#34;</span><span class="o">)</span>
<span class="n">Student</span> <span class="nf">getStudentBySidAndSex</span><span class="o">(</span><span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sid&#34;</span><span class="o">)</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sex&#34;</span><span class="o">)</span> <span class="n">String</span> <span class="n">sex</span><span class="o">);</span>
</code></pre></div><p>**探究：**要是我两个参数一个是基本类型一个是对象类型呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">testMapper</span><span class="o">.</span><span class="na">addStudent</span><span class="o">(</span><span class="n">100</span><span class="o">,</span> <span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小陆&#34;</span><span class="o">).</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">)));</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Insert</span><span class="o">(</span><span class="s">&#34;insert into student(sid, name, sex) values(#{sid}, #{name}, #{sex})&#34;</span><span class="o">)</span>
<span class="kt">int</span> <span class="nf">addStudent</span><span class="o">(</span><span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sid&#34;</span><span class="o">)</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;student&#34;</span><span class="o">)</span>  <span class="n">Student</span> <span class="n">student</span><span class="o">);</span>
</code></pre></div><p>那么这个时候，就出现问题了，Mybatis就不能明确这些属性是从哪里来的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="err">###</span> <span class="n">SQL</span><span class="o">:</span> <span class="n">insert</span> <span class="n">into</span> <span class="nf">student</span><span class="o">(</span><span class="n">sid</span><span class="o">,</span> <span class="n">name</span><span class="o">,</span> <span class="n">sex</span><span class="o">)</span> <span class="n">values</span><span class="o">(?,</span> <span class="o">?,</span> <span class="o">?)</span>
<span class="err">###</span> <span class="n">Cause</span><span class="o">:</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">BindingException</span><span class="o">:</span> <span class="n">Parameter</span> <span class="err">&#39;</span><span class="n">name</span><span class="err">&#39;</span> <span class="n">not</span> <span class="n">found</span><span class="o">.</span> <span class="n">Available</span> <span class="n">parameters</span> <span class="n">are</span> <span class="o">[</span><span class="n">student</span><span class="o">,</span> <span class="n">param1</span><span class="o">,</span> <span class="n">sid</span><span class="o">,</span> <span class="n">param2</span><span class="o">]</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">exceptions</span><span class="o">.</span><span class="na">ExceptionFactory</span><span class="o">.</span><span class="na">wrapException</span><span class="o">(</span><span class="n">ExceptionFactory</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">30</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">update</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">196</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">session</span><span class="o">.</span><span class="na">defaults</span><span class="o">.</span><span class="na">DefaultSqlSession</span><span class="o">.</span><span class="na">insert</span><span class="o">(</span><span class="n">DefaultSqlSession</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">181</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperMethod</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="n">MapperMethod</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">62</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperProxy$PlainMethodInvoker</span><span class="o">.</span><span class="na">invoke</span><span class="o">(</span><span class="n">MapperProxy</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">145</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">org</span><span class="o">.</span><span class="na">apache</span><span class="o">.</span><span class="na">ibatis</span><span class="o">.</span><span class="na">binding</span><span class="o">.</span><span class="na">MapperProxy</span><span class="o">.</span><span class="na">invoke</span><span class="o">(</span><span class="n">MapperProxy</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">86</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">sun</span><span class="o">.</span><span class="na">proxy</span><span class="o">.</span><span class="na">$Proxy6</span><span class="o">.</span><span class="na">addStudent</span><span class="o">(</span><span class="n">Unknown</span> <span class="n">Source</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">16</span><span class="o">)</span>
</code></pre></div><p>那么我们就通过参数名称.属性的方式去让Mybatis知道我们要用的是哪个属性：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Insert</span><span class="o">(</span><span class="s">&#34;insert into student(sid, name, sex) values(#{sid}, #{student.name}, #{student.sex})&#34;</span><span class="o">)</span>
<span class="kt">int</span> <span class="nf">addStudent</span><span class="o">(</span><span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;sid&#34;</span><span class="o">)</span> <span class="kt">int</span> <span class="n">sid</span><span class="o">,</span> <span class="nd">@Param</span><span class="o">(</span><span class="s">&#34;student&#34;</span><span class="o">)</span>  <span class="n">Student</span> <span class="n">student</span><span class="o">);</span>
</code></pre></div><p>那么如何通过注解控制缓存机制呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@CacheNamespace</span><span class="o">(</span><span class="n">readWrite</span> <span class="o">=</span> <span class="kc">false</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">MyMapper</span> <span class="o">{</span>

    <span class="nd">@Select</span><span class="o">(</span><span class="s">&#34;select * from student&#34;</span><span class="o">)</span>
    <span class="nd">@Options</span><span class="o">(</span><span class="n">useCache</span> <span class="o">=</span> <span class="kc">false</span><span class="o">)</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="nf">getAllStudent</span><span class="o">();</span>
</code></pre></div><p>使用<code>@CacheNamespace</code>注解直接定义在接口上即可，然后我们可以通过使用<code>@Options</code>来控制单个操作的缓存启用。</p>
<h3 id="探究mybatis的动态代理机制">探究Mybatis的动态代理机制</h3>
<p>在探究动态代理机制之前，我们要先聊聊什么是代理：其实顾名思义，就好比我开了个大棚，里面栽种的西瓜，那么西瓜成熟了是不是得去卖掉赚钱，而我们的西瓜非常多，一个人肯定卖不过来，肯定就要去多找几个开水果摊的帮我们卖，这就是一种代理。实际上是由水果摊老板在帮我们卖瓜，我们只告诉老板卖多少钱，而至于怎么卖的是由水果摊老板决定的。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F2020112311143434.png%3Fx-oss-process%26%2361%3Bimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhdHR5MTkyMA%26%2361%3B%26%2361%3B%2Csize_16%2Ccolor_FFFFFF%2Ct_7&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639472394&amp;t=b5590551c75049e91fc497b9920bdb83"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F2020112311143434.png%3Fx-oss-process%26%2361%3Bimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhdHR5MTkyMA%26%2361%3B%26%2361%3B%2Csize_16%2Ccolor_FFFFFF%2Ct_7&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639472394&amp;t=b5590551c75049e91fc497b9920bdb83, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F2020112311143434.png%3Fx-oss-process%26%2361%3Bimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhdHR5MTkyMA%26%2361%3B%26%2361%3B%2Csize_16%2Ccolor_FFFFFF%2Ct_7&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639472394&amp;t=b5590551c75049e91fc497b9920bdb83 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F2020112311143434.png%3Fx-oss-process%26%2361%3Bimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhdHR5MTkyMA%26%2361%3B%26%2361%3B%2Csize_16%2Ccolor_FFFFFF%2Ct_7&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639472394&amp;t=b5590551c75049e91fc497b9920bdb83 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F2020112311143434.png%3Fx-oss-process%26%2361%3Bimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhdHR5MTkyMA%26%2361%3B%26%2361%3B%2Csize_16%2Ccolor_FFFFFF%2Ct_7&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639472394&amp;t=b5590551c75049e91fc497b9920bdb83"
        title="img" /></p>
<p>那么现在我们来尝试实现一下这样的类结构，首先定义一个接口用于规范行为：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Shopper</span> <span class="o">{</span>

    <span class="c1">//卖瓜行为
</span><span class="c1"></span>    <span class="kt">void</span> <span class="nf">saleWatermelon</span><span class="o">(</span><span class="n">String</span> <span class="n">customer</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>然后需要实现一下卖瓜行为，也就是我们要告诉老板卖多少钱，这里就直接写成成功出售：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ShopperImpl</span> <span class="kd">implements</span> <span class="n">Shopper</span><span class="o">{</span>

    <span class="c1">//卖瓜行为的实现
</span><span class="c1"></span>    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">saleWatermelon</span><span class="o">(</span><span class="n">String</span> <span class="n">customer</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;成功出售西瓜给 ===&gt; &#34;</span><span class="o">+</span><span class="n">customer</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>最后老板代理后肯定要用自己的方式去出售这些西瓜，成交之后再按照我们告诉老板的价格进行出售：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ShopperProxy</span> <span class="kd">implements</span> <span class="n">Shopper</span><span class="o">{</span>

    <span class="kd">private</span> <span class="kd">final</span> <span class="n">Shopper</span> <span class="n">impl</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">ShopperProxy</span><span class="o">(</span><span class="n">Shopper</span> <span class="n">impl</span><span class="o">){</span>
        <span class="k">this</span><span class="o">.</span><span class="na">impl</span> <span class="o">=</span> <span class="n">impl</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="c1">//代理卖瓜行为
</span><span class="c1"></span>    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">saleWatermelon</span><span class="o">(</span><span class="n">String</span> <span class="n">customer</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">//首先进行 代理商讨价还价行为
</span><span class="c1"></span>        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：哥们，这瓜多少钱一斤啊？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：两块钱一斤。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：你这瓜皮子是金子做的，还是瓜粒子是金子做的？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：你瞅瞅现在哪有瓜啊，这都是大棚的瓜，你嫌贵我还嫌贵呢。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：给我挑一个。&#34;</span><span class="o">);</span>

        <span class="n">impl</span><span class="o">.</span><span class="na">saleWatermelon</span><span class="o">(</span><span class="n">customer</span><span class="o">);</span>   <span class="c1">//讨价还价成功，进行我们告诉代理商的卖瓜行为
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在我们来试试看：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">Shopper</span> <span class="n">shopper</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ShopperProxy</span><span class="o">(</span><span class="k">new</span> <span class="n">ShopperImpl</span><span class="o">());</span>
        <span class="n">shopper</span><span class="o">.</span><span class="na">saleWatermelon</span><span class="o">(</span><span class="s">&#34;小强&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>这样的操作称为静态代理，也就是说我们需要提前知道接口的定义并进行实现才可以完成代理，而Mybatis这样的是无法预知代理接口的，我们就需要用到动态代理。</p>
<p>JDK提供的反射框架就为我们很好地解决了动态代理的问题，在这里相当于对JavaSE阶段反射的内容进行一个补充。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ShopperProxy</span> <span class="kd">implements</span> <span class="n">InvocationHandler</span> <span class="o">{</span>

    <span class="n">Object</span> <span class="n">target</span><span class="o">;</span>
    <span class="kd">public</span> <span class="nf">ShopperProxy</span><span class="o">(</span><span class="n">Object</span> <span class="n">target</span><span class="o">){</span>
        <span class="k">this</span><span class="o">.</span><span class="na">target</span> <span class="o">=</span> <span class="n">target</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">Object</span> <span class="nf">invoke</span><span class="o">(</span><span class="n">Object</span> <span class="n">proxy</span><span class="o">,</span> <span class="n">Method</span> <span class="n">method</span><span class="o">,</span> <span class="n">Object</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Throwable</span> <span class="o">{</span>
        <span class="n">String</span> <span class="n">customer</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">args</span><span class="o">[</span><span class="n">0</span><span class="o">];</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：哥们，这瓜多少钱一斤啊？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：两块钱一斤。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：你这瓜皮子是金子做的，还是瓜粒子是金子做的？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：你瞅瞅现在哪有瓜啊，这都是大棚的瓜，你嫌贵我还嫌贵呢。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：行，给我挑一个。&#34;</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">method</span><span class="o">.</span><span class="na">invoke</span><span class="o">(</span><span class="n">target</span><span class="o">,</span> <span class="n">args</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>通过实现InvocationHandler来成为一个动态代理，我们发现它提供了一个invoke方法，用于调用被代理对象的方法并完成我们的代理工作。现在就可以通过<code> Proxy.newProxyInstance</code>来生成一个动态代理类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Shopper</span> <span class="n">impl</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ShopperImpl</span><span class="o">();</span>
    <span class="n">Shopper</span> <span class="n">shopper</span> <span class="o">=</span> <span class="o">(</span><span class="n">Shopper</span><span class="o">)</span> <span class="n">Proxy</span><span class="o">.</span><span class="na">newProxyInstance</span><span class="o">(</span><span class="n">impl</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">getClassLoader</span><span class="o">(),</span>
            <span class="n">impl</span><span class="o">.</span><span class="na">getClass</span><span class="o">().</span><span class="na">getInterfaces</span><span class="o">(),</span> <span class="k">new</span> <span class="n">ShopperProxy</span><span class="o">(</span><span class="n">impl</span><span class="o">));</span>
    <span class="n">shopper</span><span class="o">.</span><span class="na">saleWatermelon</span><span class="o">(</span><span class="s">&#34;小强&#34;</span><span class="o">);</span>
  	<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">shopper</span><span class="o">.</span><span class="na">getClass</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><p>通过打印类型我们发现，就是我们之前看到的那种奇怪的类：<code>class com.sun.proxy.$Proxy0</code>，因此Mybatis其实也是这样的来实现的（肯定有人问了：Mybatis是直接代理接口啊，你这个不还是要把接口实现了吗？）那我们来改改，现在我们不代理任何类了，直接做接口实现：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ShopperProxy</span> <span class="kd">implements</span> <span class="n">InvocationHandler</span> <span class="o">{</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">Object</span> <span class="nf">invoke</span><span class="o">(</span><span class="n">Object</span> <span class="n">proxy</span><span class="o">,</span> <span class="n">Method</span> <span class="n">method</span><span class="o">,</span> <span class="n">Object</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Throwable</span> <span class="o">{</span>
        <span class="n">String</span> <span class="n">customer</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">)</span> <span class="n">args</span><span class="o">[</span><span class="n">0</span><span class="o">];</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：哥们，这瓜多少钱一斤啊？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：两块钱一斤。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：你这瓜皮子是金子做的，还是瓜粒子是金子做的？&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;老板：你瞅瞅现在哪有瓜啊，这都是大棚的瓜，你嫌贵我还嫌贵呢。&#34;</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">customer</span> <span class="o">+</span> <span class="s">&#34;：行，给我挑一个。&#34;</span><span class="o">);</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Shopper</span> <span class="n">shopper</span> <span class="o">=</span> <span class="o">(</span><span class="n">Shopper</span><span class="o">)</span> <span class="n">Proxy</span><span class="o">.</span><span class="na">newProxyInstance</span><span class="o">(</span><span class="n">Shopper</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getClassLoader</span><span class="o">(),</span>
            <span class="k">new</span> <span class="n">Class</span><span class="o">[]{</span> <span class="n">Shopper</span><span class="o">.</span><span class="na">class</span> <span class="o">},</span>   <span class="c1">//因为本身就是接口，所以直接用就行
</span><span class="c1"></span>            <span class="k">new</span> <span class="n">ShopperProxy</span><span class="o">());</span>
    <span class="n">shopper</span><span class="o">.</span><span class="na">saleWatermelon</span><span class="o">(</span><span class="s">&#34;小强&#34;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">shopper</span><span class="o">.</span><span class="na">getClass</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><p>我们可以去看看Mybatis的源码。</p>
<p>Mybatis的学习差不多就到这里为止了，不过，同样类型的框架还有很多，Mybatis属于半自动框架，SQL语句依然需要我们自己编写，虽然存在一定的麻烦，但是会更加灵活，而后面我们还会学习JPA，它是全自动的框架，你几乎见不到SQL的影子！</p>
<hr>
<h2 id="使用junit进行单元测试">使用JUnit进行单元测试</h2>
<p>首先一问：我们为什么需要单元测试？</p>
<p>随着我们的项目逐渐变大，比如我们之前编写的图书管理系统，我们都是边在写边在测试，而我们当时使用的测试方法，就是直接在主方法中运行测试，但是，在很多情况下，我们的项目可能会很庞大，不可能每次都去完整地启动一个项目来测试某一个功能，这样显然会降低我们的开发效率，因此，我们需要使用单元测试来帮助我们针对于某个功能或是某个模块单独运行代码进行测试，而不是启动整个项目。</p>
<p>同时，在我们项目的维护过程中，难免会涉及到一些原有代码的修改，很有可能出现改了代码导致之前的功能出现问题（牵一发而动全身），而我们又不一定能立即察觉到，因此，我们可以提前保存一些测试用例，每次完成代码后都可以跑一遍测试用例，来确保之前的功能没有因为后续的修改而出现问题。</p>
<p>我们还可以利用单元测试来评估某个模块或是功能的耗时和性能，快速排查导致程序运行缓慢的问题，这些都可以通过单元测试来完成，可见单元测试对于开发的重要性。</p>
<h3 id="尝试junit">尝试JUnit</h3>
<p>首先需要导入JUnit依赖，我们在这里使用Junit4进行介绍，最新的Junit5放到Maven板块一起讲解，Jar包已经放在视频下方简介中，直接去下载即可。同时IDEA需要安装JUnit插件（默认是已经捆绑安装的，因此无需多余配置）</p>
<p>现在我们创建一个新的类，来编写我们的单元测试用例：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestMain</span> <span class="o">{</span>
    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">method</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我是测试用例1&#34;</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">method2</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我是测试用例2&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们可以点击类前面的测试按钮，或是单个方法前的测试按钮，如果点击类前面的测试按钮，会执行所有的测试用例。</p>
<p>运行测试后，我们发现控制台得到了一个测试结果，显示为绿色表示测试通过。</p>
<p>只需要通过打上<code>@Test</code>注解，即可将一个方法标记为测试案例，我们可以直接运行此测试案例，但是我们编写的测试方法有以下要求：</p>
<ul>
<li>方法必须是public的</li>
<li>不能是静态方法</li>
<li>返回值必须是void</li>
<li>必须是没有任何参数的方法</li>
</ul>
<p>对于一个测试案例来说，我们肯定希望测试的结果是我们所期望的一个值，因此，如果测试的结果并不是我们所期望的结果，那么这个测试就应该没有成功通过！</p>
<p>我们可以通过断言工具类来进行判定：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestMain</span> <span class="o">{</span>
    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">method</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;我是测试案例！&#34;</span><span class="o">);</span>
        <span class="n">Assert</span><span class="o">.</span><span class="na">assertEquals</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">);</span>    <span class="c1">//参数1是期盼值，参数2是实际测试结果值
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>通过运行代码后，我们发现测试过程中抛出了一个错误，并且IDEA给我们显示了期盼结果和测试结果，那么现在我们来测试一个案例，比如我们想查看冒泡排序的编写是否正确：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Test</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">method</span><span class="o">(){</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="o">{</span><span class="n">0</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">6</span><span class="o">,</span> <span class="n">9</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">1</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">8</span><span class="o">};</span>

    <span class="c1">//错误的冒泡排序
</span><span class="c1"></span>    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">arr</span><span class="o">.</span><span class="na">length</span> <span class="o">-</span> <span class="n">1</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
        <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">j</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">j</span> <span class="o">&lt;</span> <span class="n">arr</span><span class="o">.</span><span class="na">length</span> <span class="o">-</span> <span class="n">1</span> <span class="o">-</span> <span class="n">i</span><span class="o">;</span> <span class="n">j</span><span class="o">++)</span> <span class="o">{</span>
            <span class="k">if</span><span class="o">(</span><span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">&gt;</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span> <span class="o">+</span> <span class="n">1</span><span class="o">]){</span>
                <span class="kt">int</span> <span class="n">tmp</span> <span class="o">=</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">];</span>
                <span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">]</span> <span class="o">=</span> <span class="n">arr</span><span class="o">[</span><span class="n">j</span><span class="o">+</span><span class="n">1</span><span class="o">];</span>
                <span class="c1">// arr[j+1] = tmp;
</span><span class="c1"></span>            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="n">Assert</span><span class="o">.</span><span class="na">assertArrayEquals</span><span class="o">(</span><span class="k">new</span> <span class="kt">int</span><span class="o">[]{</span><span class="n">0</span><span class="o">,</span> <span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">6</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">8</span><span class="o">,</span> <span class="n">9</span><span class="o">},</span> <span class="n">arr</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>通过测试，我们发现得到的结果并不是我们想要的结果，因此现在我们需要去修改为正确的冒泡排序，修改后，测试就能正确通过了。我们还可以再通过一个案例来更加深入地了解测试，现在我们想测试从数据库中取数据是否为我们预期的数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Test</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">method</span><span class="o">(){</span>
    <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">MybatisUtil</span><span class="o">.</span><span class="na">getSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
        <span class="n">TestMapper</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
        <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">);</span>

        <span class="n">Assert</span><span class="o">.</span><span class="na">assertEquals</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小明&#34;</span><span class="o">).</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">setSid</span><span class="o">(</span><span class="n">1</span><span class="o">),</span> <span class="n">student</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>那么如果我们在进行所有的测试之前需要做一些前置操作该怎么办呢，一种办法是在所有的测试用例前面都加上前置操作，但是这样显然是很冗余的，因为一旦发生修改就需要挨个进行修改，因此我们需要更加智能的方法，我们可以通过<code>@Before</code>注解来添加测试用例开始之前的前置操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestMain</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span><span class="o">;</span>
    <span class="nd">@Before</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">before</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试前置正在初始化...&#34;</span><span class="o">);</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">()</span>
                    <span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试初始化完成，正在开始测试案例...&#34;</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">method1</span><span class="o">(){</span>
        <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">);</span>

            <span class="n">Assert</span><span class="o">.</span><span class="na">assertEquals</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小明&#34;</span><span class="o">).</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">setSid</span><span class="o">(</span><span class="n">1</span><span class="o">),</span> <span class="n">student</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试用例1通过！&#34;</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">method2</span><span class="o">(){</span>
        <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;女&#34;</span><span class="o">);</span>

            <span class="n">Assert</span><span class="o">.</span><span class="na">assertEquals</span><span class="o">(</span><span class="k">new</span> <span class="n">Student</span><span class="o">().</span><span class="na">setName</span><span class="o">(</span><span class="s">&#34;小红&#34;</span><span class="o">).</span><span class="na">setSex</span><span class="o">(</span><span class="s">&#34;女&#34;</span><span class="o">).</span><span class="na">setSid</span><span class="o">(</span><span class="n">2</span><span class="o">),</span> <span class="n">student</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试用例2通过！&#34;</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>同理，在所有的测试完成之后，我们还想添加一个收尾的动作，那么只需要使用<code>@After</code>注解即可添加结束动作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@After</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">after</span><span class="o">(){</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试结束，收尾工作正在进行...&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>有关JUnit的使用我们就暂时只介绍这么多。</p>
<hr>
<h2 id="jul日志系统">JUL日志系统</h2>
<p>首先一问：我们为什么需要日志系统？</p>
<p>我们之前一直都在使用<code>System.out.println</code>来打印信息，但是，如果项目中存在大量的控制台输出语句，会显得很凌乱，而且日志的粒度是不够细的，假如我们现在希望，项目只在debug的情况下打印某些日志，而在实际运行时不打印日志，采用直接输出的方式就很难实现了，因此我们需要使用日志框架来规范化日志输出。</p>
<p>而JDK为我们提供了一个自带的日志框架，位于<code>java.util.logging</code>包下，我们可以使用此框架来实现日志的规范化打印，使用起来非常简单：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
      	<span class="c1">// 首先获取日志打印器
</span><span class="c1"></span>        <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
      	<span class="c1">// 调用info来输出一个普通的信息，直接填写字符串即可
</span><span class="c1"></span>        <span class="n">logger</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;我是普通的日志&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们可以在主类中使用日志打印，得到日志的打印结果：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-tex" data-lang="tex">十一月 15, 2021 12:55:37 下午 com.test.Main main
信息: 我是普通的日志
</code></pre></div><p>我们发现，通过日志输出的结果会更加规范。</p>
<h3 id="jul日志讲解">JUL日志讲解</h3>
<p>日志分为7个级别，详细信息我们可以在Level类中查看：</p>
<ul>
<li>SEVERE（最高值）- 一般用于代表严重错误</li>
<li>WARNING  - 一般用于表示某些警告，但是不足以判断为错误</li>
<li>INFO （默认级别）  -  常规消息</li>
<li>CONFIG</li>
<li>FINE</li>
<li>FINER</li>
<li>FINEST（最低值）</li>
</ul>
<p>我们之前通过<code>info</code>方法直接输出的结果就是使用的默认级别的日志，我们可以通过<code>log</code>方法来设定该条日志的输出级别：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">SEVERE</span><span class="o">,</span> <span class="s">&#34;严重的错误&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">IOException</span><span class="o">(</span><span class="s">&#34;我就是错误&#34;</span><span class="o">));</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">WARNING</span><span class="o">,</span> <span class="s">&#34;警告的内容&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">,</span> <span class="s">&#34;普通的信息&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">,</span> <span class="s">&#34;级别低于普通信息&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，级别低于默认级别的日志信息，无法输出到控制台，我们可以通过设置来修改日志的打印级别：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>

    <span class="c1">//修改日志级别
</span><span class="c1"></span>    <span class="n">logger</span><span class="o">.</span><span class="na">setLevel</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">);</span>
    <span class="c1">//不使用父日志处理器
</span><span class="c1"></span>    <span class="n">logger</span><span class="o">.</span><span class="na">setUseParentHandlers</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>
    <span class="c1">//使用自定义日志处理器
</span><span class="c1"></span>    <span class="n">ConsoleHandler</span> <span class="n">handler</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ConsoleHandler</span><span class="o">();</span>
    <span class="n">handler</span><span class="o">.</span><span class="na">setLevel</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">addHandler</span><span class="o">(</span><span class="n">handler</span><span class="o">);</span>

    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">SEVERE</span><span class="o">,</span> <span class="s">&#34;严重的错误&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">IOException</span><span class="o">(</span><span class="s">&#34;我就是错误&#34;</span><span class="o">));</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">WARNING</span><span class="o">,</span> <span class="s">&#34;警告的内容&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">,</span> <span class="s">&#34;普通的信息&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">,</span> <span class="s">&#34;级别低于普通信息&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>每个<code>Logger</code>都有一个父日志打印器，我们可以通过<code>getParent()</code>来获取：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">logger</span><span class="o">.</span><span class="na">getParent</span><span class="o">().</span><span class="na">getClass</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，得到的是<code>java.util.logging.LogManager$RootLogger</code>这个类，它默认使用的是ConsoleHandler，且日志级别为INFO，由于每一个日志打印器都会直接使用父类的处理器，因此我们之前需要关闭父类然后使用我们自己的处理器。</p>
<p>我们通过使用自己日志处理器来自定义级别的信息打印到控制台，当然，日志处理器不仅仅只有控制台打印，我们也可以使用文件处理器来处理日志信息，我们继续添加一个处理器：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//添加输出到本地文件
</span><span class="c1"></span><span class="n">FileHandler</span> <span class="n">fileHandler</span> <span class="o">=</span> <span class="k">new</span> <span class="n">FileHandler</span><span class="o">(</span><span class="s">&#34;test.log&#34;</span><span class="o">);</span>
<span class="n">fileHandler</span><span class="o">.</span><span class="na">setLevel</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">WARNING</span><span class="o">);</span>
<span class="n">logger</span><span class="o">.</span><span class="na">addHandler</span><span class="o">(</span><span class="n">fileHandler</span><span class="o">);</span>
</code></pre></div><p>注意，这个时候就有两个日志处理器了，因此控制台和文件的都会生效。如果日志的打印格式我们不喜欢，我们还可以自定义打印格式，比如我们控制台处理器就默认使用的是<code>SimpleFormatter</code>，而文件处理器则是使用的<code>XMLFormatter</code>，我们可以自定义：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//使用自定义日志处理器(控制台)
</span><span class="c1"></span><span class="n">ConsoleHandler</span> <span class="n">handler</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ConsoleHandler</span><span class="o">();</span>
<span class="n">handler</span><span class="o">.</span><span class="na">setLevel</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">);</span>
<span class="n">handler</span><span class="o">.</span><span class="na">setFormatter</span><span class="o">(</span><span class="k">new</span> <span class="n">XMLFormatter</span><span class="o">());</span>
<span class="n">logger</span><span class="o">.</span><span class="na">addHandler</span><span class="o">(</span><span class="n">handler</span><span class="o">);</span>
</code></pre></div><p>我们可以直接配置为想要的打印格式，如果这些格式还不能满足你，那么我们也可以自行实现：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">setUseParentHandlers</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>

    <span class="c1">//为了让颜色变回普通的颜色，通过代码块在初始化时将输出流设定为System.out
</span><span class="c1"></span>    <span class="n">ConsoleHandler</span> <span class="n">handler</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ConsoleHandler</span><span class="o">(){{</span>
        <span class="n">setOutputStream</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">);</span>
    <span class="o">}};</span>
    <span class="c1">//创建匿名内部类实现自定义的格式
</span><span class="c1"></span>    <span class="n">handler</span><span class="o">.</span><span class="na">setFormatter</span><span class="o">(</span><span class="k">new</span> <span class="n">Formatter</span><span class="o">()</span> <span class="o">{</span>
        <span class="nd">@Override</span>
        <span class="kd">public</span> <span class="n">String</span> <span class="nf">format</span><span class="o">(</span><span class="n">LogRecord</span> <span class="n">record</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">SimpleDateFormat</span> <span class="n">format</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SimpleDateFormat</span><span class="o">(</span><span class="s">&#34;yyyy-MM-dd HH:mm:ss.SSS&#34;</span><span class="o">);</span>
            <span class="n">String</span> <span class="n">time</span> <span class="o">=</span> <span class="n">format</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="k">new</span> <span class="n">Date</span><span class="o">(</span><span class="n">record</span><span class="o">.</span><span class="na">getMillis</span><span class="o">()));</span>  <span class="c1">//格式化日志时间
</span><span class="c1"></span>            <span class="n">String</span> <span class="n">level</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="na">getLevel</span><span class="o">().</span><span class="na">getName</span><span class="o">();</span>  <span class="c1">// 获取日志级别名称
</span><span class="c1"></span>            <span class="c1">// String level = record.getLevel().getLocalizedName();   // 获取本地化名称（语言跟随系统）
</span><span class="c1"></span>            <span class="n">String</span> <span class="n">thread</span> <span class="o">=</span> <span class="n">String</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="s">&#34;%10s&#34;</span><span class="o">,</span> <span class="n">Thread</span><span class="o">.</span><span class="na">currentThread</span><span class="o">().</span><span class="na">getName</span><span class="o">());</span>  <span class="c1">//线程名称（做了格式化处理，留出10格空间）
</span><span class="c1"></span>            <span class="kt">long</span> <span class="n">threadID</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="na">getThreadID</span><span class="o">();</span>   <span class="c1">//线程ID
</span><span class="c1"></span>            <span class="n">String</span> <span class="n">className</span> <span class="o">=</span> <span class="n">String</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="s">&#34;%-20s&#34;</span><span class="o">,</span> <span class="n">record</span><span class="o">.</span><span class="na">getSourceClassName</span><span class="o">());</span>  <span class="c1">//发送日志的类名
</span><span class="c1"></span>            <span class="n">String</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="na">getMessage</span><span class="o">();</span>   <span class="c1">//日志消息
</span><span class="c1"></span>
          <span class="c1">//\033[33m作为颜色代码，30~37都有对应的颜色，38是没有颜色，IDEA能显示，但是某些地方可能不支持
</span><span class="c1"></span>            <span class="k">return</span> <span class="s">&#34;\033[38m&#34;</span> <span class="o">+</span> <span class="n">time</span> <span class="o">+</span> <span class="s">&#34;  \033[33m&#34;</span> <span class="o">+</span> <span class="n">level</span> <span class="o">+</span> <span class="s">&#34; \033[35m&#34;</span> <span class="o">+</span> <span class="n">threadID</span>
                    <span class="o">+</span> <span class="s">&#34;\033[38m --- [&#34;</span> <span class="o">+</span> <span class="n">thread</span> <span class="o">+</span> <span class="s">&#34;] \033[36m&#34;</span> <span class="o">+</span> <span class="n">className</span> <span class="o">+</span> <span class="s">&#34;\033[38m : &#34;</span> <span class="o">+</span> <span class="n">msg</span> <span class="o">+</span> <span class="s">&#34;\n&#34;</span><span class="o">;</span>
        <span class="o">}</span>
    <span class="o">});</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">addHandler</span><span class="o">(</span><span class="n">handler</span><span class="o">);</span>

    <span class="n">logger</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;我是测试消息1...&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">,</span> <span class="s">&#34;我是测试消息2...&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">WARNING</span><span class="o">,</span> <span class="s">&#34;我是测试消息3...&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>日志可以设置过滤器，如果我们不希望某些日志信息被输出，我们可以配置过滤规则：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>

    <span class="c1">//自定义过滤规则
</span><span class="c1"></span>    <span class="n">logger</span><span class="o">.</span><span class="na">setFilter</span><span class="o">(</span><span class="n">record</span> <span class="o">-&gt;</span> <span class="o">!</span><span class="n">record</span><span class="o">.</span><span class="na">getMessage</span><span class="o">().</span><span class="na">contains</span><span class="o">(</span><span class="s">&#34;普通&#34;</span><span class="o">));</span>

    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">SEVERE</span><span class="o">,</span> <span class="s">&#34;严重的错误&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">IOException</span><span class="o">(</span><span class="s">&#34;我就是错误&#34;</span><span class="o">));</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">WARNING</span><span class="o">,</span> <span class="s">&#34;警告的内容&#34;</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">,</span> <span class="s">&#34;普通的信息&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>实际上，整个日志的输出流程如下：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20210310214730384.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4NjIzMzc1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639566412&amp;t=aec06446b8338134a3dbddfaba9bde69"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20210310214730384.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4NjIzMzc1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639566412&amp;t=aec06446b8338134a3dbddfaba9bde69, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20210310214730384.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4NjIzMzc1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639566412&amp;t=aec06446b8338134a3dbddfaba9bde69 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20210310214730384.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4NjIzMzc1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639566412&amp;t=aec06446b8338134a3dbddfaba9bde69 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20210310214730384.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI4NjIzMzc1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639566412&amp;t=aec06446b8338134a3dbddfaba9bde69"
        title="img" /></p>
<h3 id="properties配置文件">Properties配置文件</h3>
<p>Properties文件是Java的一种配置文件，我们之前学习了XML，但是我们发现XML配置文件读取实在是太麻烦，那么能否有一种简单一点的配置文件呢？我们可以使用Properties文件：</p>
<pre><code class="language-properties" data-lang="properties">name=Test
desc=Description
</code></pre><p>该文件配置很简单，格式为<code>配置项=配置值</code>，我们可以直接通过<code>Properties</code>类来将其读取为一个类似于Map一样的对象：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">Properties</span> <span class="n">properties</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Properties</span><span class="o">();</span>
    <span class="n">properties</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;test.properties&#34;</span><span class="o">));</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">properties</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，<code>Properties</code>类是继承自<code>Hashtable</code>，而<code>Hashtable</code>是实现的Map接口，也就是说，<code>Properties</code>本质上就是一个Map一样的结构，它会把所有的配置项映射为一个Map，这样我们就可以快速地读取对应配置的值了。</p>
<p>我们也可以将已经存在的Properties对象放入输出流进行保存，我们这里就不保存文件了，而是直接打印到控制台，我们只需要提供输出流即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">Properties</span> <span class="n">properties</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Properties</span><span class="o">();</span>
  	<span class="c1">// properties.setProperty(&#34;test&#34;, &#34;lbwnb&#34;);  //和put效果一样
</span><span class="c1"></span>    <span class="n">properties</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;test&#34;</span><span class="o">,</span> <span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>
    <span class="n">properties</span><span class="o">.</span><span class="na">store</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">,</span> <span class="s">&#34;????&#34;</span><span class="o">);</span>
  	<span class="c1">//properties.storeToXML(System.out, &#34;????&#34;);  保存为XML格式
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们可以通过<code>System.getProperties()</code>获取系统的参数，我们来看看：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">getProperties</span><span class="o">().</span><span class="na">store</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">,</span> <span class="s">&#34;系统信息：&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><h3 id="编写日志配置文件">编写日志配置文件</h3>
<p>我们可以通过进行配置文件来规定日志打印器的一些默认值：</p>
<pre><code class="language-properties" data-lang="properties"># RootLogger 的默认处理器为
handlers= java.util.logging.ConsoleHandler
# RootLogger 的默认的日志级别
.level= CONFIG
</code></pre><p>我们来尝试使用配置文件来进行配置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
    <span class="c1">//获取日志管理器
</span><span class="c1"></span>    <span class="n">LogManager</span> <span class="n">manager</span> <span class="o">=</span> <span class="n">LogManager</span><span class="o">.</span><span class="na">getLogManager</span><span class="o">();</span>
    <span class="c1">//读取我们自己的配置文件
</span><span class="c1"></span>    <span class="n">manager</span><span class="o">.</span><span class="na">readConfiguration</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;logging.properties&#34;</span><span class="o">));</span>
    <span class="c1">//再获取日志打印器
</span><span class="c1"></span>    <span class="n">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="n">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">,</span> <span class="s">&#34;我是一条日志信息&#34;</span><span class="o">);</span>   <span class="c1">//通过自定义配置文件，我们发现默认级别不再是INFO了
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们也可以去修改<code>ConsoleHandler</code>的默认配置：</p>
<pre><code class="language-properties" data-lang="properties"># 指定默认日志级别
java.util.logging.ConsoleHandler.level = ALL
# 指定默认日志消息格式
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
# 指定默认的字符集
java.util.logging.ConsoleHandler.encoding = UTF-8
</code></pre><p>其实，我们阅读<code>ConsoleHandler</code>的源码就会发现，它就是通过读取配置文件来进行某些参数设置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">// Private method to configure a ConsoleHandler from LogManager
</span><span class="c1">// properties and/or default values as specified in the class
</span><span class="c1">// javadoc.
</span><span class="c1"></span><span class="kd">private</span> <span class="kt">void</span> <span class="nf">configure</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">LogManager</span> <span class="n">manager</span> <span class="o">=</span> <span class="n">LogManager</span><span class="o">.</span><span class="na">getLogManager</span><span class="o">();</span>
    <span class="n">String</span> <span class="n">cname</span> <span class="o">=</span> <span class="n">getClass</span><span class="o">().</span><span class="na">getName</span><span class="o">();</span>

    <span class="n">setLevel</span><span class="o">(</span><span class="n">manager</span><span class="o">.</span><span class="na">getLevelProperty</span><span class="o">(</span><span class="n">cname</span> <span class="o">+</span><span class="s">&#34;.level&#34;</span><span class="o">,</span> <span class="n">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">));</span>
    <span class="n">setFilter</span><span class="o">(</span><span class="n">manager</span><span class="o">.</span><span class="na">getFilterProperty</span><span class="o">(</span><span class="n">cname</span> <span class="o">+</span><span class="s">&#34;.filter&#34;</span><span class="o">,</span> <span class="kc">null</span><span class="o">));</span>
    <span class="n">setFormatter</span><span class="o">(</span><span class="n">manager</span><span class="o">.</span><span class="na">getFormatterProperty</span><span class="o">(</span><span class="n">cname</span> <span class="o">+</span><span class="s">&#34;.formatter&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">SimpleFormatter</span><span class="o">()));</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">setEncoding</span><span class="o">(</span><span class="n">manager</span><span class="o">.</span><span class="na">getStringProperty</span><span class="o">(</span><span class="n">cname</span> <span class="o">+</span><span class="s">&#34;.encoding&#34;</span><span class="o">,</span> <span class="kc">null</span><span class="o">));</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">setEncoding</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">ex2</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// doing a setEncoding with null should always work.
</span><span class="c1"></span>            <span class="c1">// assert false;
</span><span class="c1"></span>        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><h3 id="使用lombok快速开启日志">使用Lombok快速开启日志</h3>
<p>我们发现，如果我们现在需要全面使用日志系统，而不是传统的直接打印，那么就需要在每个类都去编写获取Logger的代码，这样显然是很冗余的，能否简化一下这个流程呢？</p>
<p>前面我们学习了Lombok，我们也体会到Lombok给我们带来的便捷，我们可以通过一个注解快速生成构造方法、Getter和Setter，同样的，Logger也是可以使用Lombok快速生成的。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Log</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;自动生成的Logger名称：&#34;</span><span class="o">+</span><span class="n">log</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;我是日志信息&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>只需要添加一个<code>@Log</code>注解即可，添加后，我们可以直接使用一个静态变量log，而它就是自动生成的Logger。我们也可以手动指定名称：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Log</span><span class="o">(</span><span class="n">topic</span> <span class="o">=</span> <span class="s">&#34;打工是不可能打工的&#34;</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;自动生成的Logger名称：&#34;</span><span class="o">+</span><span class="n">log</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;我是日志信息&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><h3 id="mybatis日志系统">Mybatis日志系统</h3>
<p>Mybatis也有日志系统，它详细记录了所有的数据库操作等，但是我们在前面的学习中没有开启它，现在我们学习了日志之后，我们就可以尝试开启Mybatis的日志系统，来监控所有的数据库操作，要开启日志系统，我们需要进行配置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;logImpl&#34;</span> <span class="na">value=</span><span class="s">&#34;STDOUT_LOGGING&#34;</span> <span class="nt">/&gt;</span>
</code></pre></div><p><code>logImpl</code>包括很多种配置项，包括 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING，而默认情况下是未配置，也就是说不打印。我们这里将其设定为STDOUT_LOGGING表示直接使用标准输出将日志信息打印到控制台，我们编写一个测试案例来看看效果：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestMain</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span><span class="o">;</span>
    <span class="nd">@Before</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">before</span><span class="o">(){</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">()</span>
                    <span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(){</span>
        <span class="k">try</span><span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">));</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">));</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们发现，两次获取学生信息，只有第一次打开了数据库连接，而第二次并没有。</p>
<p>现在我们学习了日志系统，那么我们来尝试使用日志系统输出Mybatis的日志信息：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;logImpl&#34;</span> <span class="na">value=</span><span class="s">&#34;JDK_LOGGING&#34;</span> <span class="nt">/&gt;</span>
</code></pre></div><p>将其配置为JDK_LOGGING表示使用JUL进行日志打印，因为Mybatis的日志级别都比较低，因此我们需要设置一下<code>logging.properties</code>默认的日志级别：</p>
<pre><code class="language-properties" data-lang="properties">handlers= java.util.logging.ConsoleHandler
.level= ALL
java.util.logging.ConsoleHandler.level = ALL
</code></pre><p>代码编写如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Log</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestMain</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="n">SqlSessionFactory</span> <span class="n">sqlSessionFactory</span><span class="o">;</span>
    <span class="nd">@Before</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">before</span><span class="o">(){</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">sqlSessionFactory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">()</span>
                    <span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;mybatis-config.xml&#34;</span><span class="o">));</span>
            <span class="n">LogManager</span> <span class="n">manager</span> <span class="o">=</span> <span class="n">LogManager</span><span class="o">.</span><span class="na">getLogManager</span><span class="o">();</span>
            <span class="n">manager</span><span class="o">.</span><span class="na">readConfiguration</span><span class="o">(</span><span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="s">&#34;logging.properties&#34;</span><span class="o">));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(){</span>
        <span class="k">try</span><span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">sqlSessionFactory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">mapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">toString</span><span class="o">());</span>
            <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="n">mapper</span><span class="o">.</span><span class="na">getStudentBySidAndSex</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;男&#34;</span><span class="o">).</span><span class="na">toString</span><span class="o">());</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>但是我们发现，这样的日志信息根本没法看，因此我们需要修改一下日志的打印格式，我们自己创建一个格式化类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestFormatter</span> <span class="kd">extends</span> <span class="n">Formatter</span> <span class="o">{</span>
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">format</span><span class="o">(</span><span class="n">LogRecord</span> <span class="n">record</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">SimpleDateFormat</span> <span class="n">format</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SimpleDateFormat</span><span class="o">(</span><span class="s">&#34;yyyy-MM-dd HH:mm:ss.SSS&#34;</span><span class="o">);</span>
        <span class="n">String</span> <span class="n">time</span> <span class="o">=</span> <span class="n">format</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="k">new</span> <span class="n">Date</span><span class="o">(</span><span class="n">record</span><span class="o">.</span><span class="na">getMillis</span><span class="o">()));</span>  <span class="c1">//格式化日志时间
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">time</span> <span class="o">+</span> <span class="s">&#34; : &#34;</span> <span class="o">+</span> <span class="n">record</span><span class="o">.</span><span class="na">getMessage</span><span class="o">()</span> <span class="o">+</span> <span class="s">&#34;\n&#34;</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>现在再来修改一下默认的格式化实现：</p>
<pre><code class="language-properties" data-lang="properties">handlers= java.util.logging.ConsoleHandler
.level= ALL
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = com.test.TestFormatter
</code></pre><p>现在就好看多了，当然，我们还可以继续为Mybatis添加文件日志，这里就不做演示了。</p>
<hr>
<h2 id="使用maven管理项目">使用Maven管理项目</h2>
<p>**注意：**开始之前，看看你C盘空间够不够，最好预留2GB空间以上！</p>
<p>**吐槽：**很多电脑预装系统C盘都给得巨少，就算不装软件，一些软件的缓存文件也能给你塞满，建议有时间重装一下系统重新分配一下磁盘空间。</p>
<p>Maven 翻译为&quot;专家&rdquo;、&ldquo;内行&rdquo;，是 Apache 下的一个纯 Java 开发的开源项目。基于项目对象模型（缩写：POM）概念，Maven利用一个中央信息片断能管理一个项目的构建、报告和文档等步骤。Maven 是一个项目管理工具，可以对 Java 项目进行构建、依赖管理。Maven 也可被用于构建和管理各种项目，例如 C#，Ruby，Scala 和其他语言编写的项目。Maven 曾是 Jakarta 项目的子项目，现为由 Apache 软件基金会主持的独立 Apache 项目。</p>
<p>通过Maven，可以帮助我们做：</p>
<ul>
<li>项目的自动构建，包括代码的编译、测试、打包、安装、部署等操作。</li>
<li>依赖管理，项目使用到哪些依赖，可以快速完成导入。</li>
</ul>
<p>我们之前并没有讲解如何将我们的项目打包为Jar文件运行，同时，我们导入依赖的时候，每次都要去下载对应的Jar包，这样其实是很麻烦的，并且还有可能一个Jar包依赖于另一个Jar包，就像之前使用JUnit一样，因此我们需要一个更加方便的包管理机制。</p>
<p>Maven也需要安装环境，但是IDEA已经自带了Maven环境，因此我们不需要再去进行额外的环境安装（无IDEA也能使用Maven，但是配置过程很麻烦，并且我们现在使用的都是IDEA的集成开发环境，所以这里就不讲解Maven命令行操作了）我们直接创建一个新的Maven项目即可。</p>
<h3 id="maven项目结构">Maven项目结构</h3>
<p>我们可以来看一下，一个Maven项目和我们普通的项目有什么区别：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Fimg_convert%2F910235ebc812ba94abb0f762e3914f67.png&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639621411&amp;t=2a62e7ef9b056d8cbe772e34fea0cc6f"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Fimg_convert%2F910235ebc812ba94abb0f762e3914f67.png&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639621411&amp;t=2a62e7ef9b056d8cbe772e34fea0cc6f, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Fimg_convert%2F910235ebc812ba94abb0f762e3914f67.png&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639621411&amp;t=2a62e7ef9b056d8cbe772e34fea0cc6f 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Fimg_convert%2F910235ebc812ba94abb0f762e3914f67.png&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639621411&amp;t=2a62e7ef9b056d8cbe772e34fea0cc6f 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2Fimg_convert%2F910235ebc812ba94abb0f762e3914f67.png&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639621411&amp;t=2a62e7ef9b056d8cbe772e34fea0cc6f"
        title="img" /></p>
<p>那么首先，我们需要了解一下POM文件，它相当于是我们整个Maven项目的配置文件，它也是使用XML编写的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&gt;</span>
<span class="nt">&lt;project</span> <span class="na">xmlns=</span><span class="s">&#34;http://maven.apache.org/POM/4.0.0&#34;</span>
         <span class="na">xmlns:xsi=</span><span class="s">&#34;http://www.w3.org/2001/XMLSchema-instance&#34;</span>
         <span class="na">xsi:schemaLocation=</span><span class="s">&#34;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;modelVersion&gt;</span>4.0.0<span class="nt">&lt;/modelVersion&gt;</span>

    <span class="nt">&lt;groupId&gt;</span>org.example<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>MavenTest<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>1.0-SNAPSHOT<span class="nt">&lt;/version&gt;</span>

    <span class="nt">&lt;properties&gt;</span>
        <span class="nt">&lt;maven.compiler.source&gt;</span>8<span class="nt">&lt;/maven.compiler.source&gt;</span>
        <span class="nt">&lt;maven.compiler.target&gt;</span>8<span class="nt">&lt;/maven.compiler.target&gt;</span>
    <span class="nt">&lt;/properties&gt;</span>

<span class="nt">&lt;/project&gt;</span>
</code></pre></div><p>我们可以看到，Maven的配置文件是以<code>project</code>为根节点，而<code>modelVersion</code>定义了当前模型的版本，一般是4.0.0，我们不用去修改。</p>
<p><code>groupId</code>、<code>artifactId</code>、<code>version</code>这三个元素合在一起，用于唯一区别每个项目，别人如果需要将我们编写的代码作为依赖，那么就必须通过这三个元素来定位我们的项目，我们称为一个项目的基本坐标，所有的项目一般都有自己的Maven坐标，因此我们通过Maven导入其他的依赖只需要填写这三个基本元素就可以了，无需再下载Jar文件，而是Maven自动帮助我们下载依赖并导入。</p>
<ul>
<li><code>groupId</code> 一般用于指定组名称，命名规则一般和包名一致，比如我们这里使用的是<code>org.example</code>，一个组下面可以有很多个项目。</li>
<li><code>artifactId</code> 一般用于指定项目在当前组中的唯一名称，也就是说在组中用于区分于其他项目的标记。</li>
<li><code>version</code> 代表项目版本，随着我们项目的开发和改进，版本号也会不断更新，就像LOL一样，每次赛季更新都会有一个大版本更新，我们的Maven项目也是这样，我们可以手动指定当前项目的版本号，其他人使用我们的项目作为依赖时，也可以根本版本号进行选择（这里的SNAPSHOT代表快照，一般表示这是一个处于开发中的项目，正式发布项目一般只带版本号）</li>
</ul>
<p><code>properties</code>中一般都是一些变量和选项的配置，我们这里指定了JDK的源代码和编译版本为1.8，无需进行修改。</p>
<h3 id="maven依赖导入">Maven依赖导入</h3>
<p>现在我们尝试使用Maven来帮助我们快速导入依赖，我们需要导入之前的JDBC驱动依赖、JUnit依赖、Mybatis依赖、Lombok依赖，那么如何使用Maven来管理依赖呢？</p>
<p>我们可以创建一个<code>dependencies</code>节点：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependencies&gt;</span>
    //里面填写的就是所有的依赖
<span class="nt">&lt;/dependencies&gt;</span>
</code></pre></div><p>那么现在就可以向节点中填写依赖了，那么我们如何知道每个依赖的坐标呢？我们可以在：https://mvnrepository.com/ 进行查询（可能打不开，建议用流量，或是直接百度某个项目的Maven依赖），我们直接搜索lombok即可，打开后可以看到已经给我们写出了依赖的坐标：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.projectlombok<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>lombok<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>1.18.22<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;scope&gt;</span>provided<span class="nt">&lt;/scope&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>我们直接将其添加到<code>dependencies</code>节点中即可，现在我们来编写一个测试用例看看依赖导入成功了没有：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">Student</span> <span class="n">student</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;小明&#34;</span><span class="o">,</span> <span class="n">18</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">student</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Data</span>
<span class="nd">@AllArgsConstructor</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">age</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>项目运行成功，表示成功导入了依赖。那么，Maven是如何进行依赖管理呢，以致于如此便捷的导入依赖，我们来看看Maven项目的依赖管理流程：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201901%2F20190106202802893827.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639624645&amp;t=75fdf146baa915fbba88918895f92b81"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201901%2F20190106202802893827.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639624645&amp;t=75fdf146baa915fbba88918895f92b81, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201901%2F20190106202802893827.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639624645&amp;t=75fdf146baa915fbba88918895f92b81 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201901%2F20190106202802893827.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639624645&amp;t=75fdf146baa915fbba88918895f92b81 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage.bubuko.com%2Finfo%2F201901%2F20190106202802893827.png&amp;refer=http%3A%2F%2Fimage.bubuko.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1639624645&amp;t=75fdf146baa915fbba88918895f92b81"
        title="img" /></p>
<p>通过流程图我们得知，一个项目依赖一般是存储在中央仓库中，也有可能存储在一些其他的远程仓库（私服），几乎所有的依赖都被放到了中央仓库中，因此，Maven可以直接从中央仓库中下载大部分的依赖（Maven第一次导入依赖是需要联网的），远程仓库中下载之后 ，会暂时存储在本地仓库，我们会发现我们本地存在一个<code>.m2</code>文件夹，这就是Maven本地仓库文件夹，默认建立在C盘，如果你C盘空间不足，会出现问题！</p>
<p>在下次导入依赖时，如果Maven发现本地仓库中就已经存在某个依赖，那么就不会再去远程仓库下载了。</p>
<p>可能在导入依赖时，小小伙伴们会出现卡顿的问题，我们建议配置一下IDEA自带的Maven插件远程仓库地址，我们打开IDEA的安装目录，找到<code>安装根目录/plugins/maven/lib/maven3/conf</code>文件夹，找到<code>settings.xml</code>文件，打开编辑：</p>
<p>找到mirros标签，添加以下内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;mirror&gt;</span>
      <span class="nt">&lt;id&gt;</span>nexus-aliyun<span class="nt">&lt;/id&gt;</span>
      <span class="nt">&lt;mirrorOf&gt;</span>*<span class="nt">&lt;/mirrorOf&gt;</span>
      <span class="nt">&lt;name&gt;</span>Nexus aliyun<span class="nt">&lt;/name&gt;</span>
      <span class="nt">&lt;url&gt;</span>http://maven.aliyun.com/nexus/content/groups/public<span class="nt">&lt;/url&gt;</span>
<span class="nt">&lt;/mirror&gt;</span> 
</code></pre></div><p>这样，我们就将默认的远程仓库地址（国外），配置为国内的阿里云仓库地址了（依赖的下载速度就会快起来了）</p>
<h3 id="maven依赖作用域">Maven依赖作用域</h3>
<p>除了三个基本的属性用于定位坐标外，依赖还可以添加以下属性：</p>
<ul>
<li><strong>type</strong>：依赖的类型，对于项目坐标定义的packaging。大部分情况下，该元素不必声明，其默认值为jar</li>
<li><strong>scope</strong>：依赖的范围（作用域，着重讲解）</li>
<li><strong>optional</strong>：标记依赖是否可选</li>
<li><strong>exclusions</strong>：用来排除传递性依赖（一个项目有可能依赖于其他项目，就像我们的项目，如果别人要用我们的项目作为依赖，那么就需要一起下载我们项目的依赖，如Lombok）</li>
</ul>
<p>我们着重来讲解一下<code>scope</code>属性，它决定了依赖的作用域范围：</p>
<ul>
<li><strong>compile</strong> ：为默认的依赖有效范围。如果在定义依赖关系的时候，没有明确指定依赖有效范围的话，则默认采用该依赖有效范围。此种依赖，在编译、运行、测试时均有效。</li>
<li><strong>provided</strong> ：在编译、测试时有效，但是在运行时无效，也就是说，项目在运行时，不需要此依赖，比如我们上面的Lombok，我们只需要在编译阶段使用它，编译完成后，实际上已经转换为对应的代码了，因此Lombok不需要在项目运行时也存在。</li>
<li><strong>runtime</strong> ：在运行、测试时有效，但是在编译代码时无效。比如我们如果需要自己写一个JDBC实现，那么肯定要用到JDK为我们指定的接口，但是实际上在运行时是不用自带JDK的依赖，因此只保留我们自己写的内容即可。</li>
<li><strong>test</strong> ：只在测试时有效，例如：JUnit，我们一般只会在测试阶段使用JUnit，而实际项目运行时，我们就用不到测试了，那么我们来看看，导入JUnit的依赖：</li>
</ul>
<p>同样的，我们可以在网站上搜索Junit的依赖，我们这里导入最新的JUnit5作为依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.junit.jupiter<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>junit-jupiter<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>5.8.1<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;scope&gt;</span>test<span class="nt">&lt;/scope&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>我们所有的测试用例全部编写到Maven项目给我们划分的test目录下，位于此目录下的内容不会在最后被打包到项目中，只用作开发阶段测试使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MainTest</span> <span class="o">{</span>

    <span class="nd">@Test</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(){</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;测试&#34;</span><span class="o">);</span>
      	<span class="c1">//Assert在JUnit5时名称发生了变化Assertions
</span><span class="c1"></span>        <span class="n">Assertions</span><span class="o">.</span><span class="na">assertArrayEquals</span><span class="o">(</span><span class="k">new</span> <span class="kt">int</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">},</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">});</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>因此，一般仅用作测试的依赖如JUnit只保留在测试中即可，那么现在我们再来添加JDBC和Mybatis的依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>mysql<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>mysql-connector-java<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>8.0.27<span class="nt">&lt;/version&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.mybatis<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>mybatis<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>3.5.7<span class="nt">&lt;/version&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>我们发现，Maven还给我们提供了一个<code>resource</code>文件夹，我们可以将一些静态资源，比如配置文件，放入到这个文件夹中，项目在打包时会将资源文件夹中文件一起打包的Jar中，比如我们在这里编写一个Mybatis的配置文件：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34; ?&gt;</span>
<span class="cp">&lt;!DOCTYPE configuration
</span><span class="cp">        PUBLIC &#34;-//mybatis.org//DTD Config 3.0//EN&#34;
</span><span class="cp">        &#34;http://mybatis.org/dtd/mybatis-3-config.dtd&#34;&gt;</span>
<span class="nt">&lt;configuration&gt;</span>
    <span class="nt">&lt;settings&gt;</span>
        <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;mapUnderscoreToCamelCase&#34;</span> <span class="na">value=</span><span class="s">&#34;true&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;cacheEnabled&#34;</span> <span class="na">value=</span><span class="s">&#34;true&#34;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;setting</span> <span class="na">name=</span><span class="s">&#34;logImpl&#34;</span> <span class="na">value=</span><span class="s">&#34;JDK_LOGGING&#34;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/settings&gt;</span>
    <span class="c">&lt;!-- 需要在environments的上方 --&gt;</span>
    <span class="nt">&lt;typeAliases&gt;</span>
        <span class="nt">&lt;package</span> <span class="na">name=</span><span class="s">&#34;com.test.entity&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/typeAliases&gt;</span>
    <span class="nt">&lt;environments</span> <span class="na">default=</span><span class="s">&#34;development&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;environment</span> <span class="na">id=</span><span class="s">&#34;development&#34;</span><span class="nt">&gt;</span>
            <span class="nt">&lt;transactionManager</span> <span class="na">type=</span><span class="s">&#34;JDBC&#34;</span><span class="nt">/&gt;</span>
            <span class="nt">&lt;dataSource</span> <span class="na">type=</span><span class="s">&#34;POOLED&#34;</span><span class="nt">&gt;</span>
                <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;driver&#34;</span> <span class="na">value=</span><span class="s">&#34;com.mysql.cj.jdbc.Driver&#34;</span><span class="nt">/&gt;</span>
                <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;url&#34;</span> <span class="na">value=</span><span class="s">&#34;jdbc:mysql://localhost:3306/study&#34;</span><span class="nt">/&gt;</span>
                <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;username&#34;</span> <span class="na">value=</span><span class="s">&#34;test&#34;</span><span class="nt">/&gt;</span>
                <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;password&#34;</span> <span class="na">value=</span><span class="s">&#34;123456&#34;</span><span class="nt">/&gt;</span>
            <span class="nt">&lt;/dataSource&gt;</span>
        <span class="nt">&lt;/environment&gt;</span>
    <span class="nt">&lt;/environments&gt;</span>
    <span class="nt">&lt;mappers&gt;</span>
        <span class="nt">&lt;mapper</span> <span class="na">class=</span><span class="s">&#34;com.test.mapper.TestMapper&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/mappers&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div><p>现在我们创建一下测试用例，顺便带大家了解一下Junit5的一些比较方便的地方：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MainTest</span> <span class="o">{</span>

    <span class="c1">//因为配置文件位于内部，我们需要使用Resources类的getResourceAsStream来获取内部的资源文件
</span><span class="c1"></span>    <span class="kd">private</span> <span class="kd">static</span> <span class="n">SqlSessionFactory</span> <span class="n">factory</span><span class="o">;</span>

    <span class="c1">//在JUnit5中@Before被废弃，它被细分了：
</span><span class="c1"></span>    <span class="nd">@BeforeAll</span> <span class="c1">// 一次性开启所有测试案例只会执行一次 (方法必须是static)
</span><span class="c1"></span>    <span class="c1">// @BeforeEach 一次性开启所有测试案例每个案例开始之前都会执行一次
</span><span class="c1"></span>    <span class="nd">@SneakyThrows</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">before</span><span class="o">(){</span>
        <span class="n">factory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SqlSessionFactoryBuilder</span><span class="o">()</span>
                <span class="o">.</span><span class="na">build</span><span class="o">(</span><span class="n">Resources</span><span class="o">.</span><span class="na">getResourceAsStream</span><span class="o">(</span><span class="s">&#34;mybatis.xml&#34;</span><span class="o">));</span>
    <span class="o">}</span>


    <span class="nd">@DisplayName</span><span class="o">(</span><span class="s">&#34;Mybatis数据库测试&#34;</span><span class="o">)</span>  <span class="c1">//自定义测试名称
</span><span class="c1"></span>    <span class="nd">@RepeatedTest</span><span class="o">(</span><span class="n">3</span><span class="o">)</span>  <span class="c1">//自动执行多次测试
</span><span class="c1"></span>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(){</span>
        <span class="k">try</span> <span class="o">(</span><span class="n">SqlSession</span> <span class="n">sqlSession</span> <span class="o">=</span> <span class="n">factory</span><span class="o">.</span><span class="na">openSession</span><span class="o">(</span><span class="kc">true</span><span class="o">)){</span>
            <span class="n">TestMapper</span> <span class="n">testMapper</span> <span class="o">=</span> <span class="n">sqlSession</span><span class="o">.</span><span class="na">getMapper</span><span class="o">(</span><span class="n">TestMapper</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">testMapper</span><span class="o">.</span><span class="na">getStudentBySid</span><span class="o">(</span><span class="n">1</span><span class="o">));</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>那么就有人提问了，如果我需要的依赖没有上传的远程仓库，而是只有一个Jar怎么办呢？我们可以使用第四种作用域：</p>
<ul>
<li><strong>system</strong>：作用域和provided是一样的，但是它不是从远程仓库获取，而是直接导入本地Jar包：</li>
</ul>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
     <span class="nt">&lt;groupId&gt;</span>javax.jntm<span class="nt">&lt;/groupId&gt;</span>
     <span class="nt">&lt;artifactId&gt;</span>lbwnb<span class="nt">&lt;/artifactId&gt;</span>
     <span class="nt">&lt;version&gt;</span>2.0<span class="nt">&lt;/version&gt;</span>
     <span class="nt">&lt;scope&gt;</span>system<span class="nt">&lt;/scope&gt;</span>
     <span class="nt">&lt;systemPath&gt;</span>C://学习资料/4K高清无码/test.jar<span class="nt">&lt;/systemPath&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>比如上面的例子，如果scope为system，那么我们需要添加一个systemPath来指定jar文件的位置，这里就不再演示了。</p>
<h3 id="maven可选依赖">Maven可选依赖</h3>
<p>当项目中的某些依赖不希望被使用此项目作为依赖的项目使用时，我们可以给依赖添加<code>optional</code>标签表示此依赖是可选的，默认在导入依赖时，不会导入可选的依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;optional&gt;</span>true<span class="nt">&lt;/optional&gt;</span>
</code></pre></div><p>比如Mybatis的POM文件中，就存在大量的可选依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
  <span class="nt">&lt;groupId&gt;</span>org.slf4j<span class="nt">&lt;/groupId&gt;</span>
  <span class="nt">&lt;artifactId&gt;</span>slf4j-api<span class="nt">&lt;/artifactId&gt;</span>
  <span class="nt">&lt;version&gt;</span>1.7.30<span class="nt">&lt;/version&gt;</span>
  <span class="nt">&lt;optional&gt;</span>true<span class="nt">&lt;/optional&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;dependency&gt;</span>
  <span class="nt">&lt;groupId&gt;</span>org.slf4j<span class="nt">&lt;/groupId&gt;</span>
  <span class="nt">&lt;artifactId&gt;</span>slf4j-log4j12<span class="nt">&lt;/artifactId&gt;</span>
  <span class="nt">&lt;version&gt;</span>1.7.30<span class="nt">&lt;/version&gt;</span>
  <span class="nt">&lt;optional&gt;</span>true<span class="nt">&lt;/optional&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;dependency&gt;</span>
  <span class="nt">&lt;groupId&gt;</span>log4j<span class="nt">&lt;/groupId&gt;</span>
  <span class="nt">&lt;artifactId&gt;</span>log4j<span class="nt">&lt;/artifactId&gt;</span>
  <span class="nt">&lt;version&gt;</span>1.2.17<span class="nt">&lt;/version&gt;</span>
  <span class="nt">&lt;optional&gt;</span>true<span class="nt">&lt;/optional&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
 ...
</code></pre></div><p>由于Mybatis要支持多种类型的日志，需要用到很多种不同的日志框架，因此需要导入这些依赖来做兼容，但是我们项目中并不一定会使用这些日志框架作为Mybatis的日志打印器，因此这些日志框架仅Mybatis内部做兼容需要导入使用，而我们可以选择不使用这些框架或是选择其中一个即可，也就是说我们导入Mybatis之后想用什么日志框架再自己加就可以了。</p>
<h3 id="maven排除依赖">Maven排除依赖</h3>
<p>我们了解了可选依赖，现在我们可以让使用此项目作为依赖的项目默认不使用可选依赖，但是如果存在那种不是可选依赖，但是我们导入此项目有不希望使用此依赖该怎么办呢，这个时候我们就可以通过排除依赖来防止添加不必要的依赖：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.junit.jupiter<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>junit-jupiter<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>5.8.1<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;scope&gt;</span>test<span class="nt">&lt;/scope&gt;</span>
    <span class="nt">&lt;exclusions&gt;</span>
        <span class="nt">&lt;exclusion&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>org.junit.jupiter<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>junit-jupiter-engine<span class="nt">&lt;/artifactId&gt;</span>
        <span class="nt">&lt;/exclusion&gt;</span>
    <span class="nt">&lt;/exclusions&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></div><p>我们这里演示了排除JUnit的一些依赖，我们可以在外部库中观察排除依赖之后和之前的效果。</p>
<h3 id="maven继承关系">Maven继承关系</h3>
<p>一个Maven项目可以继承自另一个Maven项目，比如多个子项目都需要父项目的依赖，我们就可以使用继承关系来快速配置。</p>
<p>我们右键左侧栏，新建一个模块，来创建一个子项目：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&gt;</span>
<span class="nt">&lt;project</span> <span class="na">xmlns=</span><span class="s">&#34;http://maven.apache.org/POM/4.0.0&#34;</span>
         <span class="na">xmlns:xsi=</span><span class="s">&#34;http://www.w3.org/2001/XMLSchema-instance&#34;</span>
         <span class="na">xsi:schemaLocation=</span><span class="s">&#34;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;parent&gt;</span>
        <span class="nt">&lt;artifactId&gt;</span>MavenTest<span class="nt">&lt;/artifactId&gt;</span>
        <span class="nt">&lt;groupId&gt;</span>org.example<span class="nt">&lt;/groupId&gt;</span>
        <span class="nt">&lt;version&gt;</span>1.0-SNAPSHOT<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;/parent&gt;</span>
    <span class="nt">&lt;modelVersion&gt;</span>4.0.0<span class="nt">&lt;/modelVersion&gt;</span>

    <span class="nt">&lt;artifactId&gt;</span>ChildModel<span class="nt">&lt;/artifactId&gt;</span>

    <span class="nt">&lt;properties&gt;</span>
        <span class="nt">&lt;maven.compiler.source&gt;</span>8<span class="nt">&lt;/maven.compiler.source&gt;</span>
        <span class="nt">&lt;maven.compiler.target&gt;</span>8<span class="nt">&lt;/maven.compiler.target&gt;</span>
    <span class="nt">&lt;/properties&gt;</span>

<span class="nt">&lt;/project&gt;</span>
</code></pre></div><p>我们可以看到，IDEA默认给我们添加了一个parent节点，表示此Maven项目是父Maven项目的子项目，子项目直接继承父项目的<code>groupId</code>，子项目会直接继承父项目的所有依赖，除非依赖添加了optional标签，我们来编写一个测试用例尝试一下:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">lombok.extern.java.Log</span><span class="o">;</span>

<span class="nd">@Log</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;我是日志信息&#34;</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>可以看到，子项目也成功继承了Lombok依赖。</p>
<p>我们还可以让父Maven项目统一管理所有的依赖，包括版本号等，子项目可以选取需要的作为依赖，而版本全由父项目管理，我们可以将<code>dependencies</code>全部放入<code>dependencyManagement</code>节点，这样父项目就完全作为依赖统一管理。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependencyManagement&gt;</span>
    <span class="nt">&lt;dependencies&gt;</span>
        <span class="nt">&lt;dependency&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>org.projectlombok<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>lombok<span class="nt">&lt;/artifactId&gt;</span>
            <span class="nt">&lt;version&gt;</span>1.18.22<span class="nt">&lt;/version&gt;</span>
            <span class="nt">&lt;scope&gt;</span>provided<span class="nt">&lt;/scope&gt;</span>
        <span class="nt">&lt;/dependency&gt;</span>
        <span class="nt">&lt;dependency&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>org.junit.jupiter<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>junit-jupiter<span class="nt">&lt;/artifactId&gt;</span>
            <span class="nt">&lt;version&gt;</span>5.8.1<span class="nt">&lt;/version&gt;</span>
            <span class="nt">&lt;scope&gt;</span>test<span class="nt">&lt;/scope&gt;</span>
        <span class="nt">&lt;/dependency&gt;</span>
        <span class="nt">&lt;dependency&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>mysql<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>mysql-connector-java<span class="nt">&lt;/artifactId&gt;</span>
            <span class="nt">&lt;version&gt;</span>8.0.27<span class="nt">&lt;/version&gt;</span>
        <span class="nt">&lt;/dependency&gt;</span>
        <span class="nt">&lt;dependency&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>org.mybatis<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>mybatis<span class="nt">&lt;/artifactId&gt;</span>
            <span class="nt">&lt;version&gt;</span>3.5.7<span class="nt">&lt;/version&gt;</span>
        <span class="nt">&lt;/dependency&gt;</span>
    <span class="nt">&lt;/dependencies&gt;</span>
<span class="nt">&lt;/dependencyManagement&gt;</span>
</code></pre></div><p>我们发现，子项目的依赖失效了，因为现在父项目没有依赖，而是将所有的依赖进行集中管理，子项目需要什么再拿什么即可，同时子项目无需指定版本，所有的版本全部由父项目决定，子项目只需要使用即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependencies&gt;</span>
    <span class="nt">&lt;dependency&gt;</span>
        <span class="nt">&lt;groupId&gt;</span>org.projectlombok<span class="nt">&lt;/groupId&gt;</span>
        <span class="nt">&lt;artifactId&gt;</span>lombok<span class="nt">&lt;/artifactId&gt;</span>
        <span class="nt">&lt;scope&gt;</span>provided<span class="nt">&lt;/scope&gt;</span>
    <span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;/dependencies&gt;</span>
</code></pre></div><p>当然，父项目如果还存在dependencies节点的话，里面的内依赖依然是直接继承：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependencies&gt;</span>
    <span class="nt">&lt;dependency&gt;</span>
        <span class="nt">&lt;groupId&gt;</span>org.junit.jupiter<span class="nt">&lt;/groupId&gt;</span>
        <span class="nt">&lt;artifactId&gt;</span>junit-jupiter<span class="nt">&lt;/artifactId&gt;</span>
        <span class="nt">&lt;version&gt;</span>5.8.1<span class="nt">&lt;/version&gt;</span>
        <span class="nt">&lt;scope&gt;</span>test<span class="nt">&lt;/scope&gt;</span>
    <span class="nt">&lt;/dependency&gt;</span>
<span class="nt">&lt;/dependencies&gt;</span>

<span class="nt">&lt;dependencyManagement&gt;</span>
    <span class="nt">&lt;dependencies&gt;</span>
      ...
</code></pre></div><h3 id="maven常用命令">Maven常用命令</h3>
<p>我们可以看到在IDEA右上角Maven板块中，每个Maven项目都有一个生命周期，实际上这些是Maven的一些插件，每个插件都有各自的功能，比如：</p>
<ul>
<li><code>clean</code>命令，执行后会清理整个<code>target</code>文件夹，在之后编写Springboot项目时可以解决一些缓存没更新的问题。</li>
<li><code>validate</code>命令可以验证项目的可用性。</li>
<li><code>compile</code>命令可以将项目编译为.class文件。</li>
<li><code>install</code>命令可以将当前项目安装到本地仓库，以供其他项目导入作为依赖使用</li>
<li><code>verify</code>命令可以按顺序执行每个默认生命周期阶段（<code>validate</code>，<code>compile</code>，<code>package</code>等）</li>
</ul>
<h3 id="maven测试项目">Maven测试项目</h3>
<p>通过使用<code>test</code>命令，可以一键测试所有位于test目录下的测试案例，请注意有以下要求：</p>
<ul>
<li>测试类的名称必须是以<code>Test</code>结尾，比如<code>MainTest</code></li>
<li>测试方法上必须标注<code>@Test</code>注解，实测<code>@RepeatedTest</code>无效</li>
</ul>
<p>这是由于JUnit5比较新，我们需要重新配置插件升级到高版本，才能完美的兼容Junit5：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;build&gt;</span>
    <span class="nt">&lt;plugins&gt;</span>
        <span class="nt">&lt;plugin&gt;</span>
            <span class="nt">&lt;groupId&gt;</span>org.apache.maven.plugins<span class="nt">&lt;/groupId&gt;</span>
            <span class="nt">&lt;artifactId&gt;</span>maven-surefire-plugin<span class="nt">&lt;/artifactId&gt;</span>
            <span class="c">&lt;!-- JUnit 5 requires Surefire version 2.22.0 or higher --&gt;</span>
            <span class="nt">&lt;version&gt;</span>2.22.0<span class="nt">&lt;/version&gt;</span>
        <span class="nt">&lt;/plugin&gt;</span>
    <span class="nt">&lt;/plugins&gt;</span>
<span class="nt">&lt;/build&gt;</span>
</code></pre></div><p>现在<code>@RepeatedTest</code>、<code>@BeforeAll</code>也能使用了。</p>
<h3 id="maven打包项目">Maven打包项目</h3>
<p>我们的项目在编写完成之后，要么作为Jar依赖，供其他模型使用，要么就作为一个可以执行的程序，在控制台运行，我们只需要直接执行<code>package</code>命令就可以直接对项目的代码进行打包，生成jar文件。</p>
<p>当然，以上方式仅适用于作为Jar依赖的情况，如果我们需要打包一个可执行文件，那么我不仅需要将自己编写的类打包到Jar中，同时还需要将依赖也一并打包到Jar中，因为我们使用了别人为我们通过的框架，自然也需要运行别人的代码，我们需要使用另一个插件来实现一起打包：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;plugin&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>maven-assembly-plugin<span class="nt">&lt;/artifactId&gt;</span>
    <span class="nt">&lt;version&gt;</span>3.1.0<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;configuration&gt;</span>
        <span class="nt">&lt;descriptorRefs&gt;</span>
            <span class="nt">&lt;descriptorRef&gt;</span>jar-with-dependencies<span class="nt">&lt;/descriptorRef&gt;</span>
        <span class="nt">&lt;/descriptorRefs&gt;</span>
        <span class="nt">&lt;archive&gt;</span>
            <span class="nt">&lt;manifest&gt;</span>
                <span class="nt">&lt;addClasspath&gt;</span>true<span class="nt">&lt;/addClasspath&gt;</span>
                <span class="nt">&lt;mainClass&gt;</span>com.test.Main<span class="nt">&lt;/mainClass&gt;</span>
            <span class="nt">&lt;/manifest&gt;</span>
        <span class="nt">&lt;/archive&gt;</span>
    <span class="nt">&lt;/configuration&gt;</span>
    <span class="nt">&lt;executions&gt;</span>
        <span class="nt">&lt;execution&gt;</span>
            <span class="nt">&lt;id&gt;</span>make-assembly<span class="nt">&lt;/id&gt;</span>
            <span class="nt">&lt;phase&gt;</span>package<span class="nt">&lt;/phase&gt;</span>
            <span class="nt">&lt;goals&gt;</span>
                <span class="nt">&lt;goal&gt;</span>single<span class="nt">&lt;/goal&gt;</span>
            <span class="nt">&lt;/goals&gt;</span>
        <span class="nt">&lt;/execution&gt;</span>
    <span class="nt">&lt;/executions&gt;</span>
<span class="nt">&lt;/plugin&gt;</span>
</code></pre></div><p>在打包之前也会执行一次test命令，来保证项目能够正常运行，当测试出现问题时，打包将无法完成，我们也可以手动跳过，选择<code>执行Maven目标</code>来手动执行Maven命令，输入<code>mvn package -Dmaven.test.skip=true </code>来以跳过测试的方式进行打包。</p>
<p>最后得到我们的Jar文件，在同级目录下输入<code>java -jar xxxx.jar</code>来运行我们打包好的Jar可执行程序（xxx代表文件名称）</p>
<ul>
<li><code>deploy</code>命令用于发布项目到本地仓库和远程仓库，一般情况下用不到，这里就不做讲解了。</li>
<li><code>site</code>命令用于生成当前项目的发布站点，暂时不需要了解。</li>
</ul>
<p>我们之前还讲解了多模块项目，那么多模块下父项目存在一个<code>packing</code>打包类型标签，所有的父级项目的packing都为pom，packing默认是jar类型，如果不作配置，maven会将该项目打成jar包。作为父级项目，还有一个重要的属性，那就是modules，通过modules标签将项目的所有子项目引用进来，在build父级项目时，会根据子模块的相互依赖关系整理一个build顺序，然后依次build。</p>
<hr>
<h2 id="实战基于mybatisjullombokmaven的图书管理系统带单元测试">实战：基于Mybatis+JUL+Lombok+Maven的图书管理系统（带单元测试）</h2>
<p>项目需求：</p>
<ul>
<li>在线录入学生信息和书籍信息</li>
<li>查询书籍信息列表</li>
<li>查询学生信息列表</li>
<li>查询借阅信息列表</li>
<li>完整的日志系统</li>
</ul>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/">Java连接数据库</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-02-16</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库" data-hashtags="Java连接数据库"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-hashtag="Java连接数据库"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库" data-image="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库" data-description="Java连接数据库"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库" data-description="Java连接数据库"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/java%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93/" data-title="Java连接数据库"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%E5%BE%92%E6%89%8B%E5%86%99%E7%9A%84avl%E7%AB%9F%E7%84%B6%E6%AF%94stl%E4%B8%AD%E7%9A%84%E7%BA%A2%E9%BB%91%E6%A0%91%E6%95%88%E7%8E%87%E6%9B%B4%E9%AB%98/" class="prev" rel="prev" title="徒手写的AVL竟然比STL中的红黑树效率更高？✨"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/c&#43;&#43;%E6%89%8B%E6%92%95%E5%93%88%E5%B8%8C%E8%A1%A8%E8%AF%A6%E8%A7%A3/" class="next" rel="next" title="C/C&#43;&#43;手撕哈希表详解">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
